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