【问题标题】:error: request for member ‘stream’ in something not a structure or union错误:在不是结构或联合的东西中请求成员“流”
【发布时间】:2012-01-17 01:01:43
【问题描述】:

我正在尝试创建一个要读取的命令流,但我遇到了编译问题或分段错误。我想访问我的 struct command_stream 中的成员,但是当我运行它时,我会得到“错误:在不是结构或联合的东西中请求成员 'stream'”或分段错误。我的代码如下所示。

typedef struct command_stream *command_stream_t;

struct command_stream
{  
    int stream[100];
    int test;                                                                                                                                            
};

//get_next_byte is function that returns next byte in stream
//get_next_byte_argument is pointer to FILE

command_stream_t
make_command_stream (int (*get_next_byte) (void *),void *get_next_byte_argument)
{

  command_stream_t * ptr = checked_malloc(sizeof(struct command_stream));
  int c;
  int count = 0;
  while((c = get_next_byte(get_next_byte_argument)) != EOF )
  {

      //(*ptr)->stream[0] = 0;
      //(*ptr)->test = 0;                                                                                                                                
      //ptr->test = 0;
      //ptr->stream[count] = c;
      count++;
      break;
  }
  return 0;
}

///////////////////

checked_malloc 是一个本质上是 malloc 的函数。 get_next_byte 本质上是 getc,获取文件中的下一个字符。 问题来自ptr。如果我尝试 ptr->test 或 ptr->stream[count],我会收到错误“在非结构或联合的东西中请求成员‘流’”。 如果我尝试 (*ptr)->stream[0] 或 (*ptr)->test,则不会出现编译错误,但会出现分段错误。怎么了?

【问题讨论】:

  • 它要么编译要么不编译 - 是什么?你说“但我会得到错误......或分段错误”

标签: c linux segmentation-fault


【解决方案1】:

您的类型声明与您的用法不一致。因为您有 typedef 将 command_stream_t 定义为指向结构的指针,这意味着您的变量 ptr 实际上是指向指向结构的指针的指针。您要么需要从 typedef 中删除 *,要么从 ptr 的声明中删除 *。

【讨论】:

    【解决方案2】:

    ptr 的类型为command_stream_t*,与struct command_stream ** 相同。如果您希望您的ptr 具有command_stream_t* 类型,那么您应该将您的typedef 从typedef struct command_stream* command_stream_t 更改为typedef struct command_stream command_stream_t。通过这样做,您可以按照自己的意愿使用ptr-><field>

    也就是说,(*ptr)-><field> 不会返回有效地址。因此出现了段错误。

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      相关资源
      最近更新 更多