从C中的函数返回一个字符串 [英] Returning a string from a function in C
问题描述
我有我想返回一个字符串C函数。
如果我打印返回前,然后我看到croc_data_0186.idx字符串
如果我尝试和打印则返回我看到croc_data_á☼字符串
有人能看到我在做什么错了?
问题的功能:
的char * getSegmentFileName(FILE *文件,诠释linelength个,INT行号)
{
字符* fileNameString; fseek的(文件,行号* linelength个,SEEK_SET); 焦线[linelength个]
与fgets(行,linelength个,文件); 字符* lineElements [3];
lineElements [0] = strtok的(行,:);
lineElements [1] = strtok的(NULL,:);
lineElements [2] = strtok的(NULL,:); fileNameString = lineElements [2]; 的printf(getSegmentFileName fileNameString是:%S \\ r \\ n,fileNameString); 返回fileNameString;
}
调用code:
INT indexSearch(FILE *文件的char *值,INT低,诠释高,字符* segmentFileName)
{
... segmentFileName = getSegmentFileName(文件,linelength个,中旬);
的printf(indexSearch:segmentFilename3是:%S \\ r \\ n,segmentFileName); ...
}
您正在返回一个指向本地数据,这是不是在函数返回后有效。你必须合理分配字符串。
这既可以在调用函数来完成,通过提供一个缓冲到被调用的功能,并将其复制字符串到提供的缓冲区。像这样的:
字符segmentFileName [SOME_SIZE]
getSegmentFileName(文件,linelength个,中旬,segmentFileName);
和 getSegmentFileName
功能:
无效getSegmentFileName(FILE *文件,诠释linelength个,诠释LINENUMBER,字符* segmentFileName)
{
/ * ... * / 的strcpy(segmentFileName,fileNameString);
}
另外一个解决办法是分配字符串内存在 getSegmentFileName
:
的strdup回报(fileNameString);
但你要记住免费
字符串后面。
I have a c function that I want to return a string.
If I print the string before it is returned then I see croc_data_0186.idx
If I try and print the string that is returned then I see croc_data_á☼
Can anyone see what I am doing wrong?
Problem function:
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;
}
Calling code:
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);
...
}
You are returning a pointer to local data, which is not valid after the function returns. You have to allocate the string properly.
This can be done in either the calling function, by supplying a buffer to the called function, and it copies the string over to the supplied buffer. Like this:
char segmentFileName[SOME_SIZE];
getSegmentFileName(file, lineLength, mid, segmentFileName);
and the getSegmentFileName
function:
void getSegmentFileName(FILE *file, int lineLength, int lineNumber, char *segmentFileName)
{
/* ... */
strcpy(segmentFileName, fileNameString);
}
The other solution is to allocate the memory for the string in getSegmentFileName
:
return strdup(fileNameString);
but then you have to remember to free
the string later.
这篇关于从C中的函数返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!