<分区>
Possible Duplicate:
Pointer to local variable
Can a local variable's memory be accessed outside its scope?
海湾合作委员会 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;
}