开发者

How to use structure in a structure?

This coulde be a dumm question, but i can't figure it out what i am doing wrong( i haven't used two structures in each other ).

I have two structures:

struct test
{
    struct ddata* difference;
    int diff;
};
struct test *MSG; 

struct ddata  
{
    char *filename;
    char *size;
};
struct ddata *difference

And i want to give them values this way (and my program freezes out here):

  MSG->difference = difference;  
  MSG->diff = diff;

So what am i doing wrong?

Thanks in advance!

kampi

EDIT:

The differenc开发者_如何转开发e struct variable is created in one of my function (and in there i want to give value to my MSG structure). The MSG struct variable is declared globally(i don't know if this is relevant or not). The difference value is declared and filled up this way:

struct ddata *difference = (struct ddata *) malloc( dif * sizeof *difference );    
memset( difference, 0, dif * sizeof *difference ); 
...
...
...
difference[diff].filename = strdup( primary[i].filename );
difference[diff].size = strdup( primary[i].size );
diff++;

I hope i gave you what you need.


Are you initializing MSG before using it? It has to point someplace valid before anything is assigned into it. One way to do that is

MSG = malloc (sizeof *MSG);

Then it would be valid to set fields in *MSG, as you are doing.


Maybe you forgot to do something like this:

MSG = (test* )malloc(sizeof(test));

?


Also remember to call

free(MSG);

Also you can check your code using Valgrind which would have spotted that stack dump. Here is any example.

valgrind -v --tool=memcheck --leak-check=full --track-origins=yes ./your_application

Hope this helps,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜