我有一个非常基本的问题,需要帮助。我试图了解动态分配的内存(在堆上)的范围是什么。
#include <stdio.h>
#include <malloc.h>
//-----Struct def-------
struct node {
int x;
int y;
};
//------GLOBAL DATA------
//-----FUNC DEFINITION----
void funct(){
t->x = 5; //**can I access 't' allocated on heap in main over here ?**
t->y = 6; //**can I access 't' allocated on heap in main over here ?**
printf ("int x = %d\n", t->x);
printf ("int y = %d\n", t->y);
return;
}
//-----MAIN FUNCTION------
int main(void){
struct node * t = NULL;// and what difference will it make if I define
//it outside main() instead- as a global pointer variable
t = (struct node *) malloc (sizeof(struct node));
t->x = 7;
t->y = 12;
printf ("int x = %d\n", t->x);
printf ("int y = %d\n", t->y);
funct(); // FUNCTION CALLED**
return 0;
}
t
在这里,funct()
即使在main()
没有传递参数(指向的指针t
)的情况下分配了内存,我也可以访问结构function funct
吗?因为堆对于线程来说是公用的?如果我struct node * t = NULL
在外部定义main()
为全局变量会有什么不同并且它有什么问题吗?