//FILE 1
char *ptr="Sample";
void SomeFunction() {
cout<<ptr<<endl;
}
//FILE 2
void SomeFunction();
int main()
{
extern char ptr[];
SomeFunction();
cout<<ptr<<endl;
}
main 函数中的 ptr
正在打印一些垃圾值。请告诉我原因。
最佳答案
ptr
在文件 1 中声明为指针,在文件 2 中声明为数组。指针和数组不是一回事,即使它们有时表现相似。
确保您的 extern
声明与其定义中指定的变量类型匹配。
关于c++ - 使用外部变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6452471/