Home > Mobile >  I'm trying to create a temporary array to store strings with malloc using a double pointer but
I'm trying to create a temporary array to store strings with malloc using a double pointer but

Time:10-24

This is what i'm trying to do right now but I don't know if this is this correct way to do it since I started learning C recently

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    char** input = malloc(5 * sizeof(char*));
    char buffer[10];


    for (int i = 0; i < 5; i  )
    {
        fgets(buffer,10,stdin);
        *(input i) = buffer;
        printf("%s",*(input));
        
    }
    for (int i = 0; i < 5; i  )
    {
        printf("%s",*(input i));
    }
    printf("\n");
    return 0;
}

In my head the logic seems fine but I don't know why it doesn't work

CodePudding user response:

If you tried to print the address for each input index using printf("%p", *(input i)); You will notice that all addresses are the same.

That happens because the pointers are pointed to the same array that you have defined before executing the loop, so you are just overriding the same array for each fgets()

You can fix this by creating a new array with a new reference for each iteration like this:

    char** input = malloc(5 * sizeof(char*));


    for (int i = 0; i < 5; i  )
    {
        char *buffer = malloc(10 * sizeof(char));
        fgets(buffer,10,stdin);
        *(input i) = buffer;
        printf("%s",*(input i));
        
    }

CodePudding user response:

There are a couple of things going on with your code. In your example you allocated space for 5 pointers to chars, i.e., 5 pointers which could point to strings.

You use the following code: *(input i) = buffer;. What it really does, it assigns address of array buffer to your pointers. It is the same address for all your pointers. The fgets function always overrides values in this array, as a result, all your pointers point to the same string, which was read last.

I guess, what you really wanted, is to read a string and store it. For that reason you need space for every string separately. Before doing it, however, you should remember, that strings in 'c' must be terminated by '\0', which takes an additional character position in the string. So, you need

  1. char buffer[11] = {0}; initialized to all zeros (at least the last element).
  2. fgets(buffer, 10, stdin); same way as you had it.
  3. A simple trick:
 *(input i) = malloc(11);
 strcpy(*(input 1), buffer);

Now you have every new string copied in a new location in memory and therefore preserved.

  • Related