gpt4 book ai didi

c++ - char ** 数组在 C++ 中给出段错误

转载 作者:行者123 更新时间:2023-11-30 19:21:14 25 4
gpt4 key购买 nike

我有点卡住了。看来仅仅在 char ** 数组的声明上就存在段错误。

这是我的代码的确切顺序:

printf("%d\n", size_of_array);
char** array;
printf("hello");
array = (char**)malloc(sizeof(char*)*size_of_array);

这给出了结果:

18 //my calculated size_of_array
Segmentation Fault

正如你所看到的,hello 没有输出,因此我很困惑。

另外,我还尝试过这样的说法:

array = new char*[size_of_array]; 

我并不假装自己是 C/C++ 方面最好的人,但这确实让我感到困惑。另外(如果值得注意的话),我正在使用 g++ 在 Linux 机器上进行编译。感谢您的帮助。

最佳答案

我认为您的错误一定源自代码中的其他位置,高于您发布的内容。

我刚刚运行了这个:

// I added the line below to define size_of_array since you left out that code: 
int size_of_array = 18;

然后你的代码:

printf("%d\n", size_of_array);
char** array;
printf("hello");
array = (char**)malloc(sizeof(char*)*size_of_array);

运行良好并输出:

18
helloProgram ended with exit code: 0

请注意,您在第二个 printf() 中遗漏了换行符“\n”,但这不是您的错误。

此外,您不应该强制转换 malloc (但不是错误的来源),您可以 read more about here ,只需使用:

array = malloc(sizeof(char*)*size_of_array);

然而,在 C++ 中,强制转换是必需的(希望这不会太令人困惑),但你没有说你想要 C 还是 C++?您标记了两者,顺便说一句,您的 C++ 行:

array = new char*[size_of_array];

也运行正常。

请记住,不应将 C 内存管理函数(malloc、calloc、free)与 C++ 内存管理函数(new、delete)混合在一起。这肯定会在以后引起问题,因为您可能会在某些时候将它们混合起来并释放用 new 分配的内存,或者对用 malloc 分配的内存使用 delete [] 等。

关于c++ - char ** 数组在 C++ 中给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com