c - 返回局部变量的引用

标签 c pointers

<分区>

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;
}

最佳答案

只需返回 strdup(result)。 它将分配并复制您的字符串。 但是,在外部函数中使用后必须释放结果。

您还可以在输入中获取一个缓冲区(及其大小),并用您想要的内容填充它。

关于c - 返回局部变量的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3398274/

相关文章:

c - 为什么 strlen() 函数给出了错误的值

c - 如何使用双指针从文本文件填充字符串数组?

c - C中指向数组赋值的指针

c - Makefile:文件不存在时文件不存在

c - 如何在内核空间中使用 netfilter Hook 路由拆分的数据包

c - 使用指针将字符串从源附加到目标

c++ - 指向指针数组的常量指针

c - 1 个函数中的 3 个指针 - 计算器不工作

c - 用 C 读/写大文件

c - 如何等待 exec 完成写入 C 中的管道