Can somebody tell me how to create an array of strings and load the strings into the array. I know how to use arrays with integers or even floats but not with strings.
Printable View
Can somebody tell me how to create an array of strings and load the strings into the array. I know how to use arrays with integers or even floats but not with strings.
char array[NUM_OF_STRINGS][MAX_LEN_OF_A_STRING];
And don't forget room for the null terminator.
then, to populate one element:
strcpy (array[0], "Some text");
There are other ways too.
Hi,
You can use char *names[MAXNAMES] also..
>You can use char *names[MAXNAMES] also..
Provided you're using string literals and don't intend on making modifications. Otherwise you also want to throw some dynamic memory allocation in there as well. Treating an uninitialized pointer as a string rarely works.
It's a must to get array of strings work.Quote:
Otherwise you also want to throw some dynamic memory allocation in there as well.
>It's a must to get array of strings work.
Not if you use an array of arrays as Hammer described.
Code:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNAMES 5
int main(void)
{
char buffer[1024], *str_arr[MAXNAMES];
int i;
for (i = 0; i < MAXNAMES; i++)
{
fgets(buffer, sizeof buffer, stdin);
str_arr[i] = malloc(strlen(buffer) + 1);
if (str_arr == NULL)
perror("malloc"), exit(EXIT_FAILURE);
strcpy(str_arr[i], buffer);
}
return EXIT_SUCCESS;
}
>>if (str_arr == NULL)
is incorrect, it should be
>>if (str_arr[i] == NULL)
Thanks everybody. I got Hammer's array of strings version to work.