user3436838
user3436838

Reputation: 113

structure within structure declared in a file not able to access inner structure

I have created a file msgbuf.h which is as follows:

//msgbuf.h
typedef struct msgbuf1
{
    long    mtype;
    M1      *m;
} message_buf;

typedef struct msgclient
{
    int msglen;
    int msgtype;
    char cp[100];
}M1;

And a program as check.c. Below prog is giving error that there is no M1. Why is it so? What mistake am I doing? I think the contents of file "msgbuf.h" should get copied in the prog check.c and the program should run fine. Please let me know this.

//check.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"msgbuf.h"

int main()
{
    message_buf *sbuf;
    sbuf=malloc(sizeof(sbuf));
    sbuf->m=malloc(sizeof(M1));
    sbuf->m->msglen=10;
    printf("\n%d",sbuf->m->msglen);
    printf("\n %d",sizeof(sbuf->m));
    return 0;
}

Thanks :)

Upvotes: 0

Views: 60

Answers (2)

Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

Simple, declare M1 before message_buf; .

typedef struct msgclient
{
    int msglen;
    int msgtype;
    char cp[100];
}M1;

typedef struct msgbuf1
{
    long    mtype;
    M1      *m;
} message_buf;

And read the keltar's comments below the question too.

Upvotes: 3

Remo.D
Remo.D

Reputation: 16512

You should declare M1 before using it:

//msgbuf.h
typedef struct msgclient
{
   int msglen;
   int msgtype;
   char cp[100];
}M1;

typedef struct msgbuf1
{
    long    mtype;
    M1      *m;
} message_buf;

Upvotes: 3

Related Questions