结构体calloc c
C99 gcc
我不断收到此错误。 我在 main 之外有一个结构。 在 main 内部,我尝试使用 calloc 在堆栈上分配。 我似乎无法找出问题所在。
感谢您的任何建议,
错误:')' 标记之前的预期表达式
/* global */
struct port_data_t
{
size_t task_id;
pthread_t *thread_id;
size_t start_port;
size_t number_ports;
} *port_data;
/* main function */
struct port_data_t *port_data = (struct task_data_t*) calloc(4, sizeof(port_data*));
C99 gcc
I keep getting this error. I have a struct outside main. And inside main I am trying to allocate on the stack using calloc. I can't seem to find out what is wrong.
Thanks for any advice,
error: expected expression before ‘)’ token
/* global */
struct port_data_t
{
size_t task_id;
pthread_t *thread_id;
size_t start_port;
size_t number_ports;
} *port_data;
/* main function */
struct port_data_t *port_data = (struct task_data_t*) calloc(4, sizeof(port_data*));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
应该是
calloc(4, sizeof(*port_data))
:注意变量名称之前的*。Should be
calloc(4, sizeof(*port_data))
: Note * before var name.应该是 sizeof(port_data_t) 而不是 sizeof(port_data*)。 前者是 port_data_t 结构的大小。 后者没有任何意义。
should be sizeof(port_data_t) not sizeof(port_data*). The former is the size of a port_data_t struct. The latter doesn't mean anything.
尝试改变这个:
到这个:
可能会更好一点。 如果您已将
port_data
声明为全局结构,则无需将其重新声明为struct port_data_t
。 GCC 应该已经知道这一点。 当然,我会这样做:但我不喜欢将变量放入
sizeof()
中。 我尝试坚持将类型放在那里,只是出于习惯。 另外,它解决了关于如何精确地取消引用指针的任何歧义,这在这种情况下会让您陷入困境。Try changing this:
To this:
Might work a little better. If you've declaring
port_data
as a global struct, you don't need to re-declare it as astruct port_data_t
. GCC should already know that. Of course, how I would do it is this:But I don't like putting variables in
sizeof()
. I try to stick with putting types in there, just out of habit. Plus, it resolves any ambiguities about how exactly a pointer needs to be dereferenced, which is tripping you up in this case.正如 Jeffamaphone 所指出的,task_data_t 是断章取义的。 Crashworks 还指出,如果您想要将结构数组放入 port_data 中,请尝试 sizeof (port_data_t) 。
使用 sizeof (port_data*) 会将 sizeof 指针分配给 port_data_t 的指针,这在大多数情况下只有那么有用。
As pointed out by Jeffamaphone, task_data_t is out of context. And also pointed out by Crashworks, try sizeof (port_data_t) if you want an array of structures into port_data.
Using sizeof (port_data*) will make it allocate sizeof pointer to pointer of port_data_t which in most cases is only so useful in most of the cases.