Hello, I have a very basic question and need help. I am trying to understand what is the scope of a dynamically allocated memory (on heap).
#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;
}
So, here can I access structure 't' in funct() even though the memory is allocated in main() without passing argument (pointer to t to function funct) - since heap is common to a thread ? And what difference will it make if I define struct node * t = NULL outside of main() as a global variable and is there anything wrong with it ? Thanks