我有代码,但没有编译
#include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned int ip;
unsigned int mask;
} nic_t;
typedef struct {
int nnic; /*number of nic*/
nic_t *nic;
} host_t;
int main(void)
{
int i, j;
host_t *host = malloc(sizeof(host_t) * 5);
for (i = 0; i < 5; i++) {
host[i]->nnic = 3;
host[i]->nic = malloc(sizeof(nic_t) * 3);
for (j = 0; j < host[i]->nnic; j++) {
host[i]->nic[j]->ip = 0x7f000001;
host[i]->nic[j]->mask = 0xffffff00;
}
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 3; j++) {
printf("ip = 0x%x, mask = 0x%x\n",
host[i]->nic[j]->ip,
host[i]->nic[j]->mask);
}
printf("\n\n");
}
return 0;
}
请向我解释我如何解决程序中的一系列结构,没有编译错误。 我有以下错误:
test.c: In function ‘main’:
test.c:18:10: error: invalid type argument of ‘->’ (have ‘host_t’)
test.c:19:10: error: invalid type argument of ‘->’ (have ‘host_t’)
test.c:21:11: error: invalid type argument of ‘->’ (have ‘host_t’)
test.c:22:11: error: invalid type argument of ‘->’ (have ‘host_t’)
test.c:28:13: error: invalid type argument of ‘->’ (have ‘host_t’)
test.c:29:13: error: invalid type argument of ‘->’ (have ‘host_t’)
感谢所有人。它有效。
答案 0 :(得分:2)
您将->
运算符与.
运算符混淆。如果您有结构st
,则可以st.member
访问其成员。如果您有结构指针st_ptr
,则st_ptr->member
是(*st_ptr).member
的缩写。在您的情况下,您将使用数组索引取消引用指针。
答案 1 :(得分:1)
host[i]
不是指针,它代表host_t
的单个实例,
因此您必须使用.
运算符 ,而不是->
运算符。
更改:(和所有其他事件)
From:
host[i]->nnic = 3;
To:
host[i].nnic = 3;
答案 2 :(得分:1)
您想使用.
而不是->
。
host[i]->nnic = 3;
应该是
host[i].nnic = 3;
答案 3 :(得分:1)
你有一组host_t
结构,而不是host_t *
指针。所以你想说,例如:
host[i].nnic = 3;
答案 4 :(得分:1)
您已有一系列结构。 host[i]
是一个结构,而不是指针。因此,您需要.
而不是->
。