Let suppose to have a function f such that it includes, in its body, the declaration of a new variable, b. I have noticed that every time f is invoked, the variable b - that should be every time created and destroyed (EDIT: not in the dynamic case, as pointed out by another (now solved) related question) - has always the same memory address.
The following very simple code shows you an example:
#include <stdio.h>
#include <stdlib.h>
void f ( void ){
int b;
printf ("%p\n", &b);
}
int main (){
int i = 0;
while (++i <= 10)
f();
return 0;
}
Output: (always the same memory address).
Is it possible to modify f in such a way that at each call it creates b always with new memory address, differently from every previous calling?
EDIT: some users suggested using a dynamic allocation of the memory, but unfortunately I still did not manage to solve the problem.
You may ignore the premise and look directly at my new formulation of the problem.
Let's consider the following code.
#include <stdio.h>
#include <stdlib.h>
void f ( void ){
int * b = malloc ( sizeof(int) );
printf ("%p\n", &b);
}
int main (){
int i = 0;
while (++i <= 10)
f();
return 0;
}
Why does it produce always the same output?
As you may easily imagine, my experience with C is limited. Every suggestion and/or reference for learning more is very welcome.
Thanks
Pss: I need to solve this problem as a step before creating some dynamics structure data, as lists or trees. The idea is that every time we add a node, the new node must refer to a new memory address in order to avoid loops. On my book there is written that a solution is to use the malloc instruction, and I am trying to fully understand why.