C语言 如何将元素添加到C中的字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4853556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add an element to a string array in C?
提问by Rafe Kettler
How do I add a new element to a string array in C?
如何将新元素添加到 C 中的字符串数组?
回答by Rafe Kettler
回答by Rafe Kettler
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).
C 中的字符串由字符数组组成。为了使用 printf 调用正确打印字符串,它必须以 NULL 字符 (\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.
添加一个新元素,即。一个字符,到字符串的末尾,移动到 NULL 字符并用新字符替换它,然后在它后面放回 NULL。这假设新角色已经有足够的空间可用。
char str[100];
char new_char = 'a';
int i = 0;
...
// adds new_char to existing string:
while(str[i] != 'char foo[25][25];
strcpy(foo[1], "hello world"); /* "puts" hello world in the 2nd cell of the array */
')
{
++i;
}
str[i++] = new_char;
str[i] = '##代码##';
回答by gspr
If you want to extend your array, you need to reallocate memory for it. Check out realloc.
如果你想扩展你的数组,你需要为它重新分配内存。退房realloc。
回答by Aif
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.
如果您静态分配了一个固定长度的数组,那么您可以只复制第 i 个元素中的数据。
##代码##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.
如果您使用了动态数组,则必须首先确保仍有空间,否则分配内存,然后以同样的方式放置您的项目。

