【问题标题】:structure within structure declared in a file not able to access inner structure文件中声明的结构中的结构无法访问内部结构
【发布时间】:2014-03-24 13:13:17
【问题描述】:

我创建了一个文件 msgbuf.h,内容如下:

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

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

还有一个名为 check.c 的程序。下面的 prog 给出了没有 M1 的错误。为什么会这样?我在做什么错? 我认为文件“msgbuf.h”的内容应该被复制到 prog check.c 中并且程序应该运行良好。请告诉我。

//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;
}

谢谢:)

【问题讨论】:

  • 应该是sbuf=malloc(sizeof(*sbuf));
  • 仅供参考 - 在第一个结构之前使用前向声明 (typedef struct M1 M1) 可以实现相同的目的,然后在稍后的某个地方定义 struct M1 { ... }(没有 typedef)。

标签: c linux struct


【解决方案1】:

简单,在message_buf之前声明M1; .

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

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

并阅读问题下方的 keltar 的 cmets。

【讨论】:

    【解决方案2】:

    您应该在使用前声明 M1:

    //msgbuf.h
    typedef struct msgclient
    {
       int msglen;
       int msgtype;
       char cp[100];
    }M1;
    
    typedef struct msgbuf1
    {
        long    mtype;
        M1      *m;
    } message_buf;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      相关资源
      最近更新 更多