I want to create a simple C program where, inside a loop, when the user inputs a string, the string automatically gets added to an array. I'm lost on how to do that at runtime. Any help would be appreciated.
Edit: For clarification, here, 10 is the max size of the array. I was thinking of initializing the array with a number and then expanding that size (probably by a multiplier) when it reaches the max size (which is 10 in this case).
Edit2: More specifically, I want it to be so that the first iteration adds a string to the array, then the second iteration adds another inputted string to the array, and so on.
For now my code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char* strings[10];
char *input_str;
printf("enter a string: ")
strings = malloc(sizeof(char)*10); //not sure if this is required but included anyway
//run a loop here to keep adding the input string
fgets((char)input_str, 1024, stdin);
}
CodePudding user response:
char* strings[10];
Notice that strings
is a non resizable array of ten pointers to char
, so it is not useful for dynamic allocation when you don't know the number of elements before hand.
I will use realloc
over a char **
and the modulo operator to detect when to realloc
, something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MULTIPLE 10
int main(void)
{
char **strings = NULL;
char str[1024];
size_t size = 0;
while (fgets(str, sizeof str, stdin))
{
if ((size % MULTIPLE) == 0)
{
char **temp = realloc(strings, sizeof *strings * (size MULTIPLE));
if (temp == NULL)
{
perror("realloc");
exit(EXIT_FAILURE);
}
strings = temp;
}
strings[size] = malloc(strlen(str) 1);
if (strings[size] == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(strings[size], str);
size ;
}
for (size_t i = 0; i < size; i )
{
printf("%s", strings[i]);
free(strings[i]);
}
free(strings);
return 0;
}