我目前正在做一个大学项目,我正在用c做一个游戏,我正在尝试制作一个基于按钮的菜单选择,并且需要能够将文本放入几个不同的菜单中。我正在尝试使用一个基于切换大小写的函数来返回按钮的文本。
char * findButtonTxt(int reference) {
char *rtnTxt[] = { NULL };
switch (reference) {
case 1:
rtnTxt[] = { "T", "O", "W", "E", "R", "_", "O", "F", "_", "P", "O", "W", "E", "R", NULL };
return rtnTxt;
break;
default:
return "T", "O", "W", "E", "R", "_", "O", "F", "_", "P", "O", "W", "E", "R", NULL;
}
}
我希望它像这样使用它
txt = findButtonTxt((4 * curMenu) + i + 1);
betterText(20, (getmaxy() - (25 + (50 * i))) - 30, txt);
这就是我到目前为止所拥有的,我需要它以这种方式返回数组,因为这是我可以使用我拥有的BGI版本来显示文本的唯一方法。
这就是目前正在运行的。
char *twrTxt[] = { "T", "O", "W", "E", "R", "_", "O", "F", "_", "P", "O", "W", "E", "R", NULL };
betterText((getmaxx() / 2), 0, twrTxt);
很抱歉问了这么长的问题。感谢你在高级课程中的帮助。
发布于 2019-03-20 07:23:12
我假设C是基于代码的。
不能将堆栈分配的数组作为指针返回。
char *rtnTxt[] = { NULL }; //Don't do this
您应该malloc一个数组,然后使用strncpy
#define MAX_STRING 256 // modify this to what ever your max string will be
char *rtnTxt = malloc(sizeof(char)*MAX_STRING);
然后在您的交换机中,您可以执行strcpy
strcpy (rtnTxt ,"What I want to copy");
然后返回结果
return rtnTxt;
以下是完整的解决方案
#define MAX_STRING 256
char * findButtonTxt(int reference) {
char *rtnTxt = malloc(sizeof(char)*MAX_STRING);
switch (reference) {
case 1:
strcpy (rtnTxt ,"Tower of power");
break;
}
return rtnTxt;
}
最后,完成后不要忘记调用的空闲,否则会发生内存泄漏:)
https://stackoverflow.com/questions/55251313
复制相似问题