将结构定义为全局变量

时间:2016-01-05 17:45:57

标签: c pointers struct global

我正在尝试将指向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
};

1 个答案:

答案 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分配内存后,您必须:

  1. 也使用StGlobal->varDouble
  2. malloc分配内存
  3. 将其分配给在函数返回后有效的其他指针。
  4. 另外。请勿在C中投放malloc的返回值。请参阅Do I cast the result of malloc?

    其他信息

    您可以通过设置编译器选项强制MSVC将文件视为C程序文件。在VS2008中,我可以在以下对话框中执行此操作。

    enter image description here

    可能有类似的方法来更改MSVC 2010中的设置。