Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Looping through an array of pointers

Tags:

c

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.

like image 354
Ben Avatar asked Apr 20 '26 23:04

Ben


1 Answers

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.

like image 111
unxnut Avatar answered Apr 23 '26 14:04

unxnut