char 指针的动态数组
我试图定义一个包含指向字符串的字符指针的动态数组。字符串可以是任意长度,所以我使用了 char 指针。我想在每次需要存储更多值时动态调整数组的大小。下面的代码给了我分段错误。我做得好吗?
int main() {
char **input=NULL;
char *buffer;
int i=0;
do {
input = (char **)realloc(input, (i+1) * sizeof(char *));
scanf("%s", &buffer);
strcpy(input[i++],buffer);
} while(strlen(buffer)!=0);
}
I am trying to define a dynamic array containing char pointers that point to strings. The string can be of any length, so i used char pointers. I want to dynamically resize the array each time I need to store more values. The following code gives me segmentation fault. Am I doing it well?
int main() {
char **input=NULL;
char *buffer;
int i=0;
do {
input = (char **)realloc(input, (i+1) * sizeof(char *));
scanf("%s", &buffer);
strcpy(input[i++],buffer);
} while(strlen(buffer)!=0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题是您将 buffer 定义为指针,但没有将其指向可以保存扫描字符串的对象,因此 scanf 在未分配的内存中写入,这实际上是坏的。您也没有分配
input[i]
,因此strcpy
也会失败。您可能想更改为使用strdup
代替:另外一些挑剔:扫描字符串时,您不需要字符串缓冲区上的
&
,因此重做像这样:并且您不应该强制转换
realloc
(或malloc
)的结果:The problem is that you define
buffer
as a pointer, but you do not point it to something that can hold the scanned string, soscanf
writes out in unallocated memory which is really bad. You also do not allocateinput[i]
sostrcpy
will also fail. You might want to change that to usestrdup
instead:Another couple of nitpicks: When scanning for a string, you do not need the
&
on the string buffer, so redo like this:And you should not cast the result of
realloc
(ormalloc
either for that matter):除了其他答案中已经列出的问题之外,循环永远不会终止,因为:
在读取至少一个字符(不包括行尾字符)之前不会返回。
In addition to the issues already listed in the other answers the loop will never terminate as:
will not return until it reads at least one character, excluding the end of line character.
您的缓冲区和输入[i]未分配。
Your buffer and your input[i] are not allocated.
您的代码中有多个问题。除非您修复所有这些问题,否则它不会起作用
缓冲区
分配内存。 Scanf 会写入稀薄的空气,如果不是下一点可以说是更严重的buffer
传递给 scanf,而不是&buffer
< /strong>input[i]
分配内存。你只是分配输入
的内存。There are multiple issues in your code. It won't work until you fix all of them
buffer
. Scanf would write into thin air, if it weren't for the next point which is arguably more seriousbuffer
to scanf, not&buffer
input[i]
. You are only allocatingmemory for
input
.缓冲区未初始化。此外, &buffer 是一个指向指针的指针,而不是您可能想要的字符数组。
buffer is uninitialized. Besides &buffer is a pointer to a pointer, not to a character array, as you probably intend.