可能重复:
指向局部变量的指针
可以在其范围之外访问局部变量的内存吗?
gcc 4.4.4 c89
在 main 中,我调用一个函数将一行文本传递给一个函数。我想对其进行一些操作。但是,这意味着该行没有用。所以在我的 get_string 函数中,我复制内容并返回结果。唯一的问题是,该结果的记忆会丢失并指向意想不到的东西。
我只是想知道如何将结果传回,而无需并且仍然保留序数行数据?
非常感谢您的任何建议,
主要代码片段:
if(fgets(line_data, (size_t)STRING_SIZE, fp) == NULL) {
fprintf(stderr, "WARNING: Text error reading file line number [ %d ]\n", i);
}
if(get_string(line_data) != NULL) {
if(strcmp(get_string(line_data), "END") == 0)
break;
}
else {
fprintf(stderr, "WARNING: Cannot get name of student at line [ %d ]\n", i);
}
/* Fill student info */
strncpy(stud[i].name, line_data, (size_t)STRING_SIZE);
调用这个函数
char* get_string(char *line_data)
{
char *quote = NULL;
char result[STRING_SIZE] = {0};
strncpy(result, line_data, (size_t)STRING_SIZE);
/* Find last occurance */
if((quote = strrchr(result, '"')) == NULL) {
fprintf(stderr, "Text file incorrectly formatted for this student\n");
return NULL;
}
/* Insert nul in place of the quote */
*quote = '\0';
/* Overwite the first quote by shifting 1 place */
memmove(result - 1, result, strlen(result) + 1);
return result;
}