0

I'm trying to write a function that reads values into a pointer array to store strings of variable lengths. The strings appear to be stored correctly in get_input, but have a null value when printed in the main function. Please see the code below:

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

void get_input(char *ptr)
{
    ptr = calloc(50, sizeof &ptr);
    printf("Type something: ");
    fgets(ptr, 50, stdin);
    int len = strlen(ptr);
    if (*(ptr + len - 1) == '\n')
        *(ptr + len - 1) = 0;
    printf("%s\n", ptr);
}

int main()
{
    char **string_array = calloc(5, sizeof(char *));
    if (string_array == NULL)
    {
        fprintf(stderr, "Unable to allocate array\n");
        exit(1);
    }

    for (size_t index = 0; index < 5; index++)
    {
        get_input(string_array[index]);
    }

    for (size_t index = 0; index < 5; index++)
    {
        printf("%s\n", *(string_array + index));
    }
}

What am I doing wrong? Why aren't the strings correctly stored?

Connor
  • 867
  • 7
  • 18
  • 1
    You are passing each `string_array` element ***by value***. That means that whatever happens to it in the function is not reflected in `main`. Declare the argument as `char **` and pass `&string_array[index]`. There *should* be a duplicate for this ... looking ... – Adrian Mole May 14 '23 at 17:48
  • 1
    OK - I found a *resonable* duplicate but would be happy to add more/better targets if anyone should find such. – Adrian Mole May 14 '23 at 17:50

1 Answers1

1

void get_input(char *ptr) - ptr is a local variable and assigning to it does not change the object you pass when you call it. You need to use the pointer to the pointer:

void get_input(char **ptr)
{
    *ptr = calloc(50, sizeof *ptr);
    printf("Type something: ");
    fgets(*ptr, 50, stdin);
    int len = strlen(*ptr);
    if ((*ptr)[len - 1] == '\n')
        (*ptr)[len - 1] = 0;
    printf("%s\n", *ptr);
}

int main()
{
    char **string_array = calloc(5, sizeof(char *));
    if (string_array == NULL)
    {
        fprintf(stderr, "Unable to allocate array\n");
        exit(1);
    }

    for (size_t index = 0; index < 5; index++)
    {
        get_input(&string_array[index]);
    }

    for (size_t index = 0; index < 5; index++)
    {
        printf("%s\n", *(string_array + index));
    }
}

https://godbolt.org/z/dWdK9jdza

0___________
  • 60,014
  • 4
  • 34
  • 74