Ben
Ben

Reputation: 5414

C - Looping through an array of pointers

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.

Upvotes: 3

Views: 5718

Answers (1)

unxnut
unxnut

Reputation: 8839

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.

Upvotes: 8

Related Questions