我正在尝试创建一个命令流来读取,但我正在编译问题或分段错误。我想访问我的struct command_stream中的成员,但是当我运行它时,我要么得到“错误:请求成员'stream'in不是结构或联合”或分段错误。我的代码看起来像这样。
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,并获取文件中的下一个char。 问题来自ptr。如果我尝试ptr-> test或ptr-> stream [count],我会收到错误“请求成员'流',而不是结构或联合”。 如果我尝试(* ptr) - > stream [0]或(* ptr) - > test,则没有编译错误,但是我遇到了分段错误。怎么了?
答案 0 :(得分:1)
您的类型声明与您的使用不一致。因为你有typedef将command_stream_t定义为struct的指针,这意味着你的变量ptr实际上是指向struct的指针。您需要从typedef中删除*或从ptr。
的声明中删除*答案 1 :(得分:1)
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>
不会返回有效地址。因此,段错误。