String array iteration causing segfault

I am populating an array of string and print it.
But it going in infinite loop and causing segfault.

char Name[][50] = {
                "yahoo",
                "rediff",
                "facebook",
                NULL
                };

main(int argc, char* argv[])
{
    int j = 0;

    while(Name[j] != NULL)
    {
            printf("j = %d    Name = %s    len = %d\n", j, Name[j], strlen(Name[j]));
            j++;
    }

    return(0);

}

output is

j = 0   Name = yahoo     len = 5
j = 1   Name = rediff len = 6
j = 2   Name = facebook       len = 8
j = 3   Name =     len = 0
j = 4   Name =     len = 0
j = 5   Name =     len = 0
j = 6   Name =     len = 0
j = 7   Name =     len = 0
j = 8   Name =    len = 0
j = 9   Name =    len = 0
.
.
.
12976 Segmentation fault      ./test_code

What is wrong with the code?

You made it an array of arrays, guaranteeing it will never be NULL. array[j] just calculates array + (j*50), which isn't going to be zero.

If you want to store a null pointer, you'll have to store pointers. Then you get address stored at (base_address + j) which is quite capable of being NULL.

char *strings[]={
                "yahoo",
                "rediff",
                "facebook",
                NULL };
1 Like

Thanks coronna for the reply.
Using while(Name[j][0] != NULL) solved my problem.

That means you cannot store an empty string in your array though -- it will be the same as NULL, i.e. first character holding a zero.

1 Like

yes it seems so and so inspite of being zero loop went infinetely.

I don't understand your question or statement.

I meant whatever you said in your second comment was correct and so inspite of being zero loop went infinetely.

alternatively like so:

#include <stdio.h>
#include <string.h>

const char * names[] = {
                "yahoo",
                "rediff",
                "facebook",
                NULL
                };

int main(int argc, char* argv[])
{
    const char ** p;
    for( p = names; *p  ;p++)
    {
            printf(" Name = %s    len = %d\n", *p, strlen(*p));
    }

    return 0;

}