Here is a quick test C program that I've coded to see how struct memory allocation works...
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int kk;
int zz;
} node;
node ** createNode(){
node** res = (node**) malloc(sizeof(node*)*10);
int i,j;
for(i= 0;i<10;i++){
res[i] = (node*) malloc(sizeof(node)*10);
for(j=0;j<10;j++){
res[i][j].kk=33;
}
}
return res;
}
int main(void) {
node ** g = createNode();
printf("%d",g[0][0].kk);
return 0;
}
This program prints the value "33". Now this has become obvious to me, but reflecting on it, I don't understand why...
Now that I think about it, shouldn't the variable g
be of type node ***
?
And the print statement look something like printf("%d",g[0][0]->kk);
?
Where in the second version, I've essentially done the same thing as my original code, but I have a pointer to a node instead of the actual node.
What is the difference between the two in terms of the first being statically allocated (I think) and the second being dynamically allocated... and shouldn't the node values I created in my createNode() function be destroyed once outside the scope of that function?
Just a little confused is all :S I need someone to clarify this for me, what is the difference between node**
and node***