下面是我的代码。编译器生成的错误为
#include<stdio.h>
struct Shelf{
int clothes;
int *books;
};
struct Shelf b;
b.clothes=5;
*(b.books)=6;
对于上述代码中的 b.clothes=5;
和 b->books=6;
语句,编译器会生成如下错误。
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
我不是 C 的初学者,我相信我写的是正确的。请解决我的问题
最佳答案
首先
你不能这样做
struct Shelf{
int clothes;
int books;
};
struct Shelf b;
b.clothes=5;
b.books=6;
在全局范围内
可以在函数内部赋值
int main (void )
{
b.clothes=5;
b.books=6;
}
或在声明中初始化值
struct Shelf b = { .clothes = 5, .books = 6 };
此外,如您所见,b
不是指针,因此使用 ->
是不正确的:使用 .
访问结构的成员。
第二个
你的结构有一个指针成员 book
struct Shelf{
int clothes;
int *books;
};
你可以做的是将它设置为另一个变量的地址,比如
int book = 6;
struct Shelf b = { .clothes = 5, .books = &book };
或者像这样为那个指针分配内存
int main (void )
{
b.clothes=5;
b.books=malloc(sizeof(int));
if (b.books != NULL)
{
*(b.books) = 6;
}
}
顺便说一句,我猜你想要一系列书籍,所以
int main (void )
{
b.clothes=5;
b.books=malloc(sizeof(int) * MAX_N_OF_BOOKS);
if (b.books != NULL)
{
for (int i=0; i<MAX_N_OF_BOOKS; i++)
b.books[i] = 6;
}
}
竞争测试代码
#include <stdio.h>
#include <stdlib.h>
struct Shelf
{
int clothes;
int *books;
};
int main(void)
{
struct Shelf b;
b.clothes = 5;
b.books = malloc(sizeof(int));
if (b.books != NULL)
{
*(b.books) = 6;
}
printf ("clothes: %d\n", b.clothes);
printf ("book: %d\n", *(b.books) );
}
输出
clothes: 5
book: 6
关于c - 为什么我的 C 代码出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873415/