I have the following C program:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
typedef struct node_t node_t;
struct node_t
{
char *name;
node_t **nodes;
};
node_t* init(int p_n)
{
node_t *node = malloc(sizeof(node_t));
node->name = "_ROOT_";
if(p_n > 0 && p_n < 10)
{
node->nodes = malloc(p_n*sizeof(node_t**));
char nbuffer[9];
int i;
for(i = 0; i < p_n; i++)
{
node_t *child = malloc(sizeof(node_t));
sprintf(nbuffer, "NAME %d", i);
child->name = nbuffer;
node->nodes[i] = child;
}
}
return node;
}
int main(int argc, char *argv[])
{
int n = 3;
node_t *ROOT = init(n);
printf("%sNODE {name:%s [%lu]}\n",
"", ROOT->name, sizeof(ROOT->nodes)/sizeof(ROOT->nodes[0])
);
assert(n == sizeof(ROOT->nodes)/sizeof(ROOT->nodes[0]));
free(ROOT);
return 0;
}
The assertion from the beginning of the main method fails and this is my problem. What I am doing wrong in the evaluation of the length of member nodes?
This post is know by me but from some reason it doesn't work for me. Why?
SK