Your both programs cause undefined behavior. Expressions grouped in braces are called block or compound expressions. Any variable defined in a block has a scope only in this block. As soon as you leave the block area, this variable ceases to exist and illegally refers to it.
int main(void) { int *a; { // block scope starts int b = 10; // b exists in this block only a = &b; } // block scope ends // *a dereferences memory which is no longer in scope // this invokes undefined behaviour printf("%d\n", *a); }
Similarly, automatic variables defined in a function have a scope function. Once the function returns, the variables that are allocated on the stack are no longer available. This explains the warning you get for your second program. If you want to return a variable from a function, you should select it dynamically.
int main(void) { int *a; a = foo(); printf("%d\n", *a); } int *foo(void) { int b = 10;
In addition, the main signature must be one of the following -
int main(void); int main(int argc, char *argv[]);
source share