将结构定义为全局变量

Defining a struct as a global variable

我正在尝试将指向 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
};
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. 也使用 malloc
  2. StGlobal->varDouble 分配内存
  3. 将其分配给其他一些指针,该指针在函数 returns 后有效。

还有。不要在 C 中转换 malloc 的 return 值。参见 Do I cast the result of malloc?

附加信息

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

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