The following is my code
int main(){
char *movies[500];
int i=0;
while(*(movies[i])!='$'){
scanf("%s",(movies[i]));
i++;
}
}
The output is a segmentation fault. Can someone please explain?
movies[i] = malloc(<size>);
Allocate memory to each pointer before writing something to it.
Your pointers movies[i] doesn't point to any valid memory location and you try to write to it which will lead to undefined behavior hence the crash.
Once done using the memory free() it accordingly
char *movies[500] is array of pointers and for each pointer you need to allocate memoryFirst, you don't have an array of arrays; you have an array of pointers. When you do that, you must allocate the individual strings as you go. If you had an array of arrays, you would be declaring it like this:
char movies[500][500]; // <<== Not recommended
However, your approach is more economical in terms of memory.
Second, your exit condition (user enters $ for the first character of the movie name) will never be true, because you always check the value before movies[i] has been populated.
Here is how you can fix this:
char buf[500];
int count = 0;
for (;;) {
scanf("%s", buf);
// Check exit condition here
if (buf[0] == '$') {
break;
}
// Make a copy
movies[count] = malloc(strlen(buf)+1);
strcpy(movies[count++], buf);
}
...
// Don't forget to free the strings that you allocated
for (int i = 0 ; i != count ; i++) {
free(movies[i]);
}
whileloop is testingmovies[i]before it reads anything into it. It should probably be ado-whileloop so it tests after reading.