这里有一些 super 简单的测试代码来详细说明我的问题:
#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
然后代码进入
while()
循环,其中它进入一个名为
prompt()
的函数,其中它进入名为
func()
的函数中,- 我想在其中访问我之前定义的变量
arr
。
- 我想在其中访问我之前定义的变量
但是,当我尝试编译这段代码(使用 gcc)时,我得到了一个错误,告诉我
error:'arr' undeclared (first used in this function)`.
此外,我收到一条警告,告诉我
warning: unused variable 'arr'
.
太奇怪了……有什么想法吗?
最佳答案
您有 2 个选择
Make the variable arr global (as mentioned by Sourav)
Pass the pointer to the arr variable to the prompt() function, and then also to func(). You can then use it in func().
您选择哪一个取决于手头的任务和项目的复杂性。
如果它是一个简单的项目并且这是一次性的,那么您可以使用全局的。
但是,随着您的项目复杂性增加,尤其是如果您要在多个地点执行此操作,我强烈建议您努力并通过选项 2。
关于无法从当前范围之外的两个范围访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30933287/