【发布时间】:2020-06-22 22:16:45
【问题描述】:
这是我的代码,我想从我的函数中返回二维数组 [10][8] 和 [10][20],但我得到一个错误! (分段错误)。
请帮帮我!!我的项目需要这个。最后我想打印这个数组,但由于错误我不能这样做。
有人可以帮我解决这个问题并打印那个吗?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
char **getWords(int level)
{
if (level == 1)
{
char **words = new char *[8];
strcpy(words[0], "Pakistan");
strcpy(words[1], "Portugal");
strcpy(words[2], "Tanzania");
strcpy(words[3], "Thailand");
strcpy(words[4], "Zimbabwe");
strcpy(words[5], "Cameroon");
strcpy(words[6], "Colombia");
strcpy(words[7], "Ethiopia");
strcpy(words[8], "Honduras");
strcpy(words[9], "Maldives");
return words;
}
//For Hard Level
else if (level == 2)
{
char **words = (char **)malloc(sizeof(char *) * 20);
strcpy(words[0], "Tajikistan");
strcpy(words[1], "Uzbekistan");
strcpy(words[2], "Azerbaijan");
strcpy(words[3], "Bangladesh");
strcpy(words[4], "Luxembourg");
strcpy(words[5], "Madagascar");
strcpy(words[6], "Mauritania");
strcpy(words[7], "Montenegro");
strcpy(words[8], "Mozambique");
strcpy(words[9], "New Zealand");
return words;
}
}
int main()
{
getWords(1);
return 0;
}
【问题讨论】:
-
在调试器中运行代码并单步执行。找出你在哪一行得到段错误。这将帮助您缩小问题的范围。如果您不知道如何使用调试器,现在是学习的好时机。
-
如果这是 c++,为什么不使用
std::vector<std::string>。它会让一切变得更容易。 -
在对字符串执行
strcpy()之前,必须为字符串分配缓冲区。 -
从函数返回一个局部指针变量简直是灾难!
words是getWords函数堆栈上的局部变量。你知道当控制从函数返回到调用行时会发生什么吗? -
在同一个指针中混合
malloc和new是一个非常糟糕的主意。无法通过指针判断您需要使用delete或free中的哪一个来重新放回内存。
标签: c++ memory-management malloc new-operator dynamic-memory-allocation