How do I add a new element to a string array in C?
-
Is your array already full? Are you trying to increase the size of your array?David Weiser– David Weiser2011-01-31 16:48:56 +00:00Commented Jan 31, 2011 at 16:48
-
Check this out, stackoverflow.com/questions/4694401/…Michael Smith– Michael Smith2011-01-31 16:51:04 +00:00Commented Jan 31, 2011 at 16:51
-
So its an array of strings, or a string (an array of chars)? While similar, both cases have their own pitfalls.PeterK– PeterK2011-02-01 17:28:35 +00:00Commented Feb 1, 2011 at 17:28
4 Answers
If it's a string, you'd just use strcat() (some docs). Just be wary that you can only extend as much as you've allowed memory for. You may have to realloc(), like another poster said.
Comments
A string in C is composed of an array of characters. In order for the string to be correctly printed using printf calls, it must be terminated by the NULL character (\0).
To add a new element ie. a character, to the end of a string, move to the NULL character & replace it with the new character, then put back the NULL after it. This assumes that sufficient space is already available for the new character.
char str[100];
char new_char = 'a';
int i = 0;
...
// adds new_char to existing string:
while(str[i] != '\0')
{
++i;
}
str[i++] = new_char;
str[i] = '\0';
2 Comments
str[i++] = new_char; is equivalent to str[i] = new_char; i++; If still in doubt refer to stackoverflow.com/q/4865599/191776It depends on what you call an array.
if you have staticaly allocated a fixed length array, then you can just copy data in the i-th element.
char foo[25][25];
strcpy(foo[1], "hello world"); /* "puts" hello world in the 2nd cell of the array */
If you have used a dynamic array, you must first insure that there is still space, otherwize allocate memory, then put your item the same way.
5 Comments
0 to 24, otherwise you write to a wrong area in memory, which may result in data loss and/or program crash. foo[1] is a pointer to the second array element, the second string.strdup? It doesn't look like the standard version.char foo[25][25]). Also you can't just assign a dynamically allocated string (a pointer) to an array. Try to compile your example...