无法从当前范围之外的两个范围访问变量?

Cannot access variable from two scopes outside the current scope?

这里有一些超级简单的测试代码来详细说明我的问题:

#include <stdio.h>
#include <string.h>
#include <stdlib.h> 

void prompt();
void func();

int main() {
    char* arr = "Hello";

    while(1) {
        prompt();
    }

    return 0;
}

void prompt() {
    func();
}

void func() {
    char* data = NULL;
    data = arr;
}

所以如你所见,我在main()函数

中定义了一个变量arr

但是,当我尝试编译这段代码(使用 gcc)时,我收到一条错误消息,告诉我

error:'arr' undeclared (first used in this function)`.

此外,我收到一条警告,告诉我

warning: unused variable 'arr'.

太奇怪了...有什么想法吗?

在您的代码中,arr 具有 main() 函数(块)作用域 #。在func()里面,不存在arr.

如果您需要从 func() 访问 arr,您需要将其设为全局。


(#)不要和lifetime混淆

您有 2 个选项

  1. Make the variable arr global (as mentioned by Sourav)

  2. Pass the pointer to the arr variable to the prompt() function, and then also to func(). You can then use it in func().

您选择哪一个取决于手头的任务和项目的复杂程度。

如果它是一个简单的项目,并且这是一次性的,那么您可以使用全局的。

但是,随着项目复杂性的增加,尤其是如果您要在多个地点执行此操作,我强烈建议您努力尝试 选项 2 .