从C函数返回字符串 [英] Returning string from C function
本文介绍了从C函数返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有在3年以上使用C,我是pretty对很多事情生疏了。
I haven't used C in over 3 years, I'm pretty rusty on a lot of things.
我知道这听起来很蠢,但此刻我不能从一个函数返回一个字符串。请假设:我不能使用文件string.h
这一点。
I know this may seem stupid but I cannot return a string from a function at the moment. Please assume that: I cannot use string.h
for this.
下面是我的code:
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return word;
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
我能捕捉到的字符串(与我的 getStr
函数),但我不能让它正确地显示(我得到的垃圾)。
I can capture the string (with my getStr
function) but I cannot get it to display correctly (I get garbage).
帮助是AP preciated。
Help is appreciated.
推荐答案
无论是分配的主叫侧堆栈上的字符串,并将其传递给你的函数:
Either allocate the string on the stack on the caller side and pass it to your function:
void getStr(char *wordd, int length) {
...
}
int main(void) {
char wordd[10 + 1];
getStr(wordd, sizeof(wordd) - 1);
...
}
,或使串静中 getStr
:
char *getStr(void) {
static char wordd[10 + 1];
...
return wordd;
}
或分配堆上的字符串:
char *getStr(int length) {
char *wordd = malloc(length + 1);
...
return wordd;
}
这篇关于从C函数返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文