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 Jan 31 '11 at 16:48
-
Check this out, http://stackoverflow.com/questions/4694401/how-to-replicate-vector-in-c/4694762#4694762 – Michael Smith Jan 31 '11 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 Feb 01 '11 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.

- 75,757
- 21
- 156
- 151
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';
-
I don't understand how that could possibly work, that code seems to null terminate the array/string before the last element? – Jan 31 '11 at 19:59
-
try it out in your compiler: in this context, `str[i++] = new_char;` is equivalent to `str[i] = new_char; i++;` If still in doubt refer to http://stackoverflow.com/q/4865599/191776 – Feb 02 '11 at 09:23
If you want to extend your array, you need to reallocate memory for it. Check out realloc
.

- 11,144
- 3
- 41
- 74
It 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.

- 11,015
- 1
- 30
- 44
-
With `strdup(foo[1], "hello world");`, should `foo[1]` always be at index 1? Say there were 5 elements in the array, would I then use `foo[6]`? thanks – Jan 31 '11 at 16:55
-
@James: You can modify elements from `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. – YasirA Jan 31 '11 at 17:03
-
Where are you getting your `strdup`? It doesn't look like the standard version. – bstpierre Jan 31 '11 at 17:39
-
-
Your array declaration syntax wrong (should be `char foo[25][25]`). Also you can't just assign a dynamically allocated string (a pointer) to an array. Try to compile your example... – Georg Fritzsche Feb 01 '11 at 14:02