0

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 ?

Edited by deceptikon: Moved to C forum

2
Contributors
4
Replies
26
Views
2 Years
Discussion Span
Last Post by sahar.97
0

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

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.