简体   繁体   中英

seg fault in an array of strings using pointers in C

What i am trying to do here is print all the elements of an array of strings,using pointers. The reason i dont use a counter is because i dont know the size of the array. I only know that it is always terminated with a null character. Running the code below gives me the elements until the last one("fri"). Then it gives me a segmentation fault. I cant really understand why. A little help would be appreciated.

#include <stdio.h>


int main(int argv,char *argc[]){

    char *array[]={"mon","tue","wed","thu","fri",'\0'};
    char **parray;
    parray=array;
    char *pword;
    pword=&**parray;
    while (**parray != '\0'){
        printf("The first letter is %c\n",**parray);
        while (*pword != '\0'){
           printf("%c",*pword);
           pword++;
        }
        parray++;
        pword=&**parray;
     }
}

This line is a problem for the last element of parray .

while (**parray != '\0'){

For the last line, *parray is NULL. By using **parray , you are dereferencing a NULL pointer. Change that line to:

while (*parray != NULL){

I suggest changing the initialization to:

char *array[]={"mon","tue","wed","thu","fri",NULL};

That is more readable.

The last element is null character. Change '\\0' to "\\0" .

The last value in array is zero - not a string containing a null. So the test involving **parray is dereferencing that zero. Either change the check to use *parray or change the last entry in array to be an empty string ("").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM