为什么我的C代码出错了

Nas*_*mad 0 c pointers

以下是我的代码.编译器生成错误

#include<stdio.h>
struct Shelf{
    int clothes;
    int *books;
};
struct Shelf b;
b.clothes=5;
*(b.books)=6;
Run Code Online (Sandbox Code Playgroud)

编译器为语句b.clothes=5;和b->books=6;上面的代码生成如下错误.

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
Run Code Online (Sandbox Code Playgroud)

我不是C的初学者,我相信我所写的是正确的.请解决我的问题

LPs*_*LPs 5

第一

你不能做这个

struct Shelf{
    int clothes;
    int books;
};
struct Shelf b;
b.clothes=5;
b.books=6;
Run Code Online (Sandbox Code Playgroud)

在全球范围内

您可以在函数内指定值

int main (void )
{
   b.clothes=5;
   b.books=6;
}
Run Code Online (Sandbox Code Playgroud)

或者在声明时初始化值

struct Shelf b = { .clothes = 5, .books = 6 };
Run Code Online (Sandbox Code Playgroud)

此外,您可以看到b不是指针,因此使用->不正确:用于.访问struct的成员.


第二

你的struct有一个指针成员 book

struct Shelf{
    int clothes;
    int *books;
};
Run Code Online (Sandbox Code Playgroud)

你可以做的是将它设置为另一个变量的地址,比如

int book = 6;
struct Shelf b = { .clothes = 5, .books = &book };
Run Code Online (Sandbox Code Playgroud)

或者为那个指针分配内存

int main (void )
{
   b.clothes=5;
   b.books=malloc(sizeof(int));
   if (b.books != NULL)
   {
       *(b.books) = 6;
   }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我想你想要一本书,所以

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

竞争测试代码

#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) );
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT

clothes: 5
book: 6
Run Code Online (Sandbox Code Playgroud)