cstringinputmallocdouble-pointer

I'm trying to create a temporary array to store strings with malloc using a double pointer but i'm running into overwrite of my previous strings


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


Solution

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