c - 为什么我的 C 代码出错

标签 c pointers

下面是我的代码。编译器生成的错误为

#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/

相关文章:

c++ - 计算鼠标点击次数 C

C: printf 未执行,可能的编译器优化?

c - 为什么我们不能像一维数组一样访问二维数组?我怎样才能访问?

c - 字符串分配给指针字符串数组和动态内存的问题

c++ - 指向 C++ 中的指针

c - Netfilter 内核模块拦截数据包并记录它们

c - BSD 上的 nftw 有何不同?

c - 关闭优化时无法解析的外部符号__aullshr

c++ - 作用域、数组和堆

C - 拆分降低了我的计算机速度