How to add an element to an array of strings in C?

How to add a new element to an array of strings in C?

+3
source share
4 answers

If this is a string, you are just using strcat()( some docs ). Just be careful that you can expand only as much as you allowed memory. You may have to realloc(), as another poster said.

+5
source

A string in C consists of an array of characters. For a line to be printed correctly using printf calls, it must be interrupted by the NULL character (\ 0).

, .. , , NULL , NULL . , .

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

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

+1
source

It depends on what you call an array.

If you statically assigned an array with a fixed length, you can simply copy the data to the ith element.

char foo[25][25];
strcpy(foo[1], "hello world"); /* "puts" hello world in the 2nd cell of the array */

If you used a dynamic array, you must first make sure that there is still space, the other allocates memory, and then place your element in the same way.

-1
source

Source: https://habr.com/ru/post/1789043/


All Articles