KeyboardSound
KeyboardSound

Reputation: 11

Problem with gets function on array of strings in C

A few line of code bellow. When program execute I can input only 2 string without problem regardless what number is n, and then input loop stops. It shows ''Input 3. string'', ''Input 4. string'' etc but without possibility to enter data. I have more code after this and everything works fine for first 2 strings but as I said I can't enter third and latter strings.

int n,i;

printf("Number of strings is: ");scanf("%d%*c",&n);

char **str=malloc(sizeof(char*)*n);

for(i=0;i<n;i++)
{
    printf("Input %d. string: ",i+1);gets(str[i]);
}

Im not sure if the problem is in memory alocation or in gets function.... Generaly I need to pass array of entered strings into function and then process each string.

Function prototip is: void func(char **str, int n);

Upvotes: 1

Views: 41

Answers (1)

KeyboardSound
KeyboardSound

Reputation: 11

Solved... Beside allocation memory for array of pointers, as I write above, I need also to allocate memory for each string, so I need for example this:

for (int j = 0; j < n; ++j) {                   
str[j] = (char *)malloc(100); }

Upvotes: 0

Related Questions