0

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?

LinuxStuff
  • 71
  • 7
moussesj94
  • 485
  • 1
  • 8
  • 27
  • 1
    [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Jun 28 '17 at 09:52
  • 2
    FYI: `sizeof(char)` is always 1. Also, there is no real benefit of allocating such a small memory. Just go with `char month[3][10]`. – Andrejs Cainikovs Jun 28 '17 at 09:57

2 Answers2

2

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]);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305