When I try to loop through the following C program, I get the error: "Segmentation fault: 11"
#include <stdio.h>
main() {
int i;
char *a[] = {
"hello",
"how are you",
"what is your name"
};
for (i = 0; a[i][0] != '\0'; i++ ) {
printf("\n%s", a[i]);
}
}
But when I replace the test in the for loop with the following, then I don't get an error and everything works fine.
for (i = 0; i < 3; i++ ) {
printf("\n%s", a[i]);
}
I'd really appreciate it if someone could explain to me why the test a[i][0] != '\0' doesn't work, and what I should be doing instead.
You need to have a terminating string that is missing. Your definition for a should be
char *a[] = {
"hello",
"how are you",
"what is your name",
""
};
Without the empty string, you are accessing a[3] that does not exist and hence, the seg fault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With