如何在 C 循环中将字符串追加到字符串数组中?
鉴于每次添加的值(因此指针指向的值正在改变),我正在努力了解如何将字符串附加到字符串数组中。我期望 array
的格式为 {"hello, "helloo", ...}
但我无法让它工作。我可以进行哪些更改使 array
正确存储它?
int size = 10;
char *string = "hello";
char c = "o";
char *array[size];
for (int i = 0; i < 10; i++) {
strcat(string, c);
array[i] = string;
}
I'm struggling to see how I can append a string to an array of strings, given that the value being added to each time (therefore the value the pointer points to is changing). I'm expecting array
to be in the format {"hello, "helloo", ...}
but I can't get this to work. What changes can I make so that array
stores this correctly?
int size = 10;
char *string = "hello";
char c = "o";
char *array[size];
for (int i = 0; i < 10; i++) {
strcat(string, c);
array[i] = string;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哎呀...这里有很多错误!
让我们回到基础知识:C 语言没有字符串的概念。在语言级别,您只有(单个)字符类型:
char
。在库级别,字符串由以 null 结尾的字符数组表示。因此,为了能够向字符串添加字符,您必须有一个正确维度的数组。顺便说一句,像
"hello"
这样的文字是一个 const 字符数组:程序员无法对其进行任何更改。因此,这里您希望能够向“hello”添加 1 到 10 个字符,因此您需要一个 16 个字符的数组:5 个字符用于 hello,10 个用于附加
o
,1 个用于 null。但这还不是全部,array
只是一个指针数组。如果array
的所有元素都指向您添加字符的同一个字符串,那么最后它们都将具有完全相同的值!必须让数组的每个元素指向不同的字符数组。假设strdup
可用,您可以编写:当您不再需要
array
时,您应该释放使用strdup
分配的所有字符串:BTW,
strdup
自 C23 起仅存在于标准 C 库中,之前它只是一个 POSIX 扩展。如果在您的系统上不可用,您可以自行创建:或者您可以通过使用真正的二维数组来避免动态分配:
Oops... there are tons of errors here!
Let us go back to the basics: C language has no notion of what a string could be. At the language level you only have the (single) character type:
char
. At the library level, a string is representented by a null terminated character array.So to be able to add a character to a string, you must have an array of the correct dimension. BTW, a litteral like
"hello"
is a const character array: the programmer cannot change anything to it.So here you want to be able to add 1 to 10 character to "hello", so you need a 16 character array: 5 for hello, 10 for the additional
o
and 1 for the null. But that is not all,array
is just an array of pointers. If all elements ofarray
point to the same string to which you add characters, at the end they will all have the very same value! You must have each element of the array to point to a different character array. Assuming thatstrdup
is available you could write:When you will no longer need
array
you should free all strings allocated withstrdup
:BTW,
strdup
is only in the standard C library since C23, it previously was just a POSIX extension. If is in not available on your system you can roll you own:Alternatively you could avoid dynamic allocation by using a true 2D array:
除非字符串是动态分配的,否则需要预先确定大小。另外,
char str_name[size]
是字符串的定义方式。Unless the string is dynamically allocated, the size needs to be pre determined. Also,
char str_name[size]
is how a string is defined.