3

How do I add a new element to a string array in C?

George Stocker
  • 57,289
  • 29
  • 176
  • 237

4 Answers4

5

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.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
2

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
1

If you want to extend your array, you need to reallocate memory for it. Check out realloc.

gspr
  • 11,144
  • 3
  • 41
  • 74
1

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.

Aif
  • 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
  • @bstpierre: you're right, code updated. @Yasir: thanks for explainations! – Aif Jan 31 '11 at 19:28
  • 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