I can’t seem to figure out what I’m doing wrong. I am simply intreating over a list of chars and trying to print them.
char *name[] = {"RGS", "O", "NRGY", "SIG", "BML-O", "BHI", "KSU", "ORN"};
void function() {
int i;
//for (i =0; i<sizeof(name) / sizeof(char); i++) {
for (i =0; name[i] != NULL; i++) {
printf ("%s \n", name[i]);
}
}
When I use the first for loop(the one commented out) it prints out the list but has two items at the end that say (NULL) and gives a segment fault. When I use the second for loop(the uncommented one), it prints everything but also gives a segment fault.
output:
RGS
O
NRGY
SIG
BML-O
BHI
KSU
ORN
Segmentation fault: 11
I don’t get any errors when compiling the code(gcc ./learningC.c) and if I comment out this function I do not get any error(it makes me think its this area of code thats the problem). I’m wondering what am I doing wrong?
For the first style of loop, you need to use
sizeof(char*), notsizeof(char). The element of the array ischar*, notchar.For the second style of loop, your array will only have a NULL at the end if you put it there: