moussesj94
moussesj94

Reputation: 505

How to save input by pointing to string array?

Here I want to save input string by pointing to an array, but the output will all change to the last inserted input.

char **month;
int row, col;
int i, j;
char name[10];

month = (char **)malloc(3*sizeof(char *));

for (int i = 0; i < 3; i++)
{
    month[i] = (char *)malloc(10*sizeof(char));

    printf("Enter name\n");

    scanf("%s", name);

    month[i] = name;
}

for (int i = 0; i < 3; i++)
{
    printf("%s\n", month[i]);
}

return 0;

Any idea how can I fix it?

Upvotes: 0

Views: 55

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409196

These two lines are problematic:

month[i] = (char *)malloc(10*sizeof(char));
...
month[i] = name;

The first allocates memory and makes month[i] point to that memory. The second line reassigns month[i] to make it point to name instead. You lose the original memory (and have a memory leak). Besides the memory leak it also means that all elements of month will point to the same memory, which will contain the last input read.

Instead of using assignment you could copy the string:

strcpy(month[i], name);

Or skip the temporary name variable and read directly into month[i]:

scanf("%9s", month[i]);

Upvotes: 2

gsamaras
gsamaras

Reputation: 73366

Change this:

month[i] = name;

to this:

strcpy(month[i], name);

since you need to use strcpy() to copy/assign a string in C.


BTW: Do I cast the result of malloc? No.

Upvotes: 0

Related Questions