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 ?

Recommended Answers

All 4 Replies

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);
}

but i do not have the size of each string

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.

ok , thank you very much

Be a part of the DaniWeb community

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