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.
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.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
Hi,
You can use char *names[MAXNAMES] also..
Saravanan.T.S.
Beginner.
>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.
My best code is written with the delete key.
It's a must to get array of strings work.Otherwise you also want to throw some dynamic memory allocation in there as well.
Saravanan.T.S.
Beginner.
>It's a must to get array of strings work.
Not if you use an array of arrays as Hammer described.
My best code is written with the delete key.
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)
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
Thanks everybody. I got Hammer's array of strings version to work.