I want to scanf array of string in c

char *bookName[n];
 for(i = 0 ; i < n ; i++){
    scanf("%s" , bookName[i]);


}

but it dose not work ,what is the problem ?

Re: string in c 80 80

You have an array of pointers to random memory, not an array of pointers to infinite memory usable by your program. This code practically begs for segmentation faults due to trashing memory. You need to either specify a size for your strings:

char bookName[N][50] = {0};

for (size_t i = 0; i < N; i++)
{
    if (scanf("%49s", bookName[i]) != 1)
    {
        break;
    }
}

Or allocate memory dynamically:

char *bookName[N] = {0};
char buf[1024];

for (size_t i = 0; i < N; i++)
{
    if (scanf("%1023s", buf) != 1)
    {
        break;
    }

    bookName[i] = malloc(strlen(buf) + 1);

    if (bookName[i] == NULL)
    {
        break;
    }

    strcpy(bookName[i], buf);
}
Re: string in c 80 80

but i do not have the size of each string

Re: string in c 80 80

This is C, there's no magic. So you'll need to acquire the size of each string somehow or make an assumption of the most reasonable largest string. I used the latter approach in the second example by using 1024 as the size of the temporary buffer. It's simpler, but there's a greater risk of failure if you choose the upper limit poorly.

Re: string in c 80 80

ok , thank you very much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.