我正在尝试将指向struct
的指针定义为全局变量,并在不同的函数中访问其变量的值。但我意识到在下一个函数调用后清除了值。难道我做错了什么?
struct St {
double* varDouble;
};
struct St* StGlobal;
void Fun1(){
double initDouble[2][1] = {{1},{2}};
StGlobal = (struct St*)malloc(sizeof(struct St));
StGlobal->varDouble = *initDouble;
};
void Func2(){
for (i =0;i<2;i++){
printf("%d\n", StGlobal->varDouble);
}
};
int main(){
Func1();
Func2(); // value of StGlobal->varDouble is no longer what was assigned to it in Func1
};
答案 0 :(得分:1)
void Fun1(){
double initDouble[2][1] = {{1},{2}};
StGlobal = (struct St*)malloc(sizeof(struct St));
// OK. StGlobal points to a memory that was returned by malloc.
// The memory will be valid after the function returns.
StGlobal->varDouble = *initDouble;
// Not OK. initDouble is a local 2D array. *initDouble is a pointer
// that is valid as long as initDouble is in scope. When the function
// returns the pointer is not valid.
};
和
void Func2(){
for (i =0;i<2;i++){
printf("%d\n", StGlobal->varDouble);
// StGlobal->varDouble is dangling pointer.
// Also, you are printing a pointer using %d. ???
// If you try to access the pointer here, the program will exhibit
// undefined behavior since it is a dangling pointer.
}
};
为StGlobal
分配内存后,您必须:
StGlobal->varDouble
或malloc
分配内存
另外。请勿在C中投放malloc
的返回值。请参阅Do I cast the result of malloc?。
其他信息
您可以通过设置编译器选项强制MSVC将文件视为C程序文件。在VS2008中,我可以在以下对话框中执行此操作。
可能有类似的方法来更改MSVC 2010中的设置。