【发布时间】:2021-11-10 23:29:33
【问题描述】:
我正在尝试从 C 中的函数访问和操作字符串列表,但由于某种原因,一旦函数中的循环通过 1 次,我就会遇到 seg 错误。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_stuff(char*** what)
{
for(int i = 0; i < sizeof(*what); ++i)
{
*what[i] = malloc(5 * sizeof(*what));
*what[i] = "hello";
printf("%s\n", *what[i]);
}
}
int main(void)
{
char** hello;
hello = malloc(20 * sizeof(*hello));
print_stuff(&hello);
}
【问题讨论】:
-
这一行:
*what[i] = "hello";可能没有做你认为它正在做的事情。研究strcpy. -
sizeof(*what)不是数组的长度,而是指针变量需要多少字节(在 64 位系统上为 8) -
这个问题的答案可能会有所帮助:Triple pointers in C: is it a matter of style?
-
在极少数情况下,您实际上需要 C 语言中的
***。这可能不是其中之一。您使用***是因为您认为您需要它,还是试图通过插入和删除*来消除警告?您可能应该找到一本好书或教程,并阅读有关指针和数组如何工作的信息。另外我建议在其他地方创建数组,而不是在名为“print_stuff”的函数内。
标签: c pointers malloc dynamic-memory-allocation