以下函数返回的指针不会无法访问吗?
char *foo( int rc )
{
switch (rc)
{
case 1: return("one");
case 2: return("two");
default: return("whatever");
}
}
Run Code Online (Sandbox Code Playgroud)
所以C/C++中局部变量的生命周期实际上只在函数内,对吧?这意味着,在char* foo(int)终止后,它返回的指针不再意味着什么?
我对本地var的生命周期有点困惑.谁能给我一个很好的澄清?
我在3年多的时间里没有使用过C,我在很多方面都很生气.
我知道这可能看起来很愚蠢,但我现在无法从函数返回一个字符串.请假设:我不能string.h用于此.
这是我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我可以捕获字符串(使用我的getStr函数)但我无法正确显示它(我得到了垃圾).
感谢帮助.
我是C初学者,这是我的C代码:
#include <stdio.h>
#include <stdlib.h>
main()
{
printf("Hello world !\n");
return 'sss';
}
Run Code Online (Sandbox Code Playgroud)
这将显示错误,
那么如何在C代码中返回一个字符串?
我有一个ac函数,我想返回一个字符串.
如果我在返回之前打印字符串,那么我会看到croc_data_0186.idx
如果我尝试打印返回的字符串,那么我会看到croc_data_á☼
谁能看到我做错了什么?
问题功能:
char* getSegmentFileName(FILE *file, int lineLength, int lineNumber)
{
char* fileNameString;
fseek(file, lineNumber * lineLength, SEEK_SET);
char line[lineLength];
fgets(line, lineLength, file);
char *lineElements[3];
lineElements[0] = strtok(line, ":");
lineElements[1] = strtok(NULL, ":");
lineElements[2] = strtok(NULL, ":");
fileNameString = lineElements[2];
printf ("getSegmentFileName fileNameString is: %s \r\n", fileNameString);
return fileNameString;
}
Run Code Online (Sandbox Code Playgroud)
来电代码:
int indexSearch(FILE *file, char* value, int low, int high, char* segmentFileName)
{
...
segmentFileName = getSegmentFileName(file, lineLength, mid);
printf ("indexSearch: segmentFilename3 is: %s \r\n", segmentFileName);
...
}
Run Code Online (Sandbox Code Playgroud)