关于struct数组的数据结构

时间:2018-03-12 15:04:16

标签: c data-structures

最近,我选了一个名为数据结构的主题。我已经创建了一个程序来试验我的知识,但不知道为什么程序不起作用。我无法弄明白,所以我在这里发帖要求解决方案。我希望人们可以帮助我。我是新手。如果我的意见令人讨厌,请忽略我的意见。

#include <stdio.h>
int main()
{
    struct Book
    {
        char title[50];
        int year;
        float price;
    };
    int i;

    struct Book books[50];
    books[0].title="Bullshit";
    books[0].year=132;
    books[0].price=146.9;

    books[1]=(struct Book){"Money",1344,189.4
    };

    for(i=0;i<2;i++)
    {
        printf("Book Title is : %s\n",books[i].title);
        printf("Book Year is %d\n",books[i].year);
        printf("Book price is %3.2f\n",books[i].price);
        printf("\n\n");
    }
}

2 个答案:

答案 0 :(得分:1)

1我会将结构的声明放在主要内部而不是内部

2尝试将char title[50]更改为char *title

#include <stdio.h>

struct Book {
    char *title;
    int year;
    float price;
};

int main() {

    int i;

    struct Book books[50];
    books[0].title = "Bullshit";
    books[0].year = 132;
    books[0].price = 146.9;

    books[1] = (struct Book) {"Money", 1344, 189.4
    };

    for (i = 0; i < 2; i++) {
        printf("Book Title is : %s\n", books[i].title);
        printf("Book Year is %d\n", books[i].year);
        printf("Book price is %3.2f\n", books[i].price);
        printf("\n\n");
    }
}

为什么它之前没有用?

c中的数组不能由=运算符分配 您可以执行类似title[0] = 'B'; title[1] = 'u', etc...。(or use strcpy which does it for you)。

的操作

char *x实际上不是一个数组,它只是指向单个字符的指针 如果我们写x = "abc",我们告诉编译器:将x设置为'a',将下一个字节设置为'b',设置在'c'旁边,然后设置为0(不是'0',只为零)。< / p>

当你执行printf("%s",x)时,printf函数会从x指定的内存中打印字符,直到看到0字节为止。

char *x = "abcd";

char *y = x;
while(*y != 0){   // this loop acts like printf("%s",x);
    printf("%c",*y);
    y++;
}

另请参阅thisthis问题。

或者,如果您使用的是c ++,而不是c,请使用std :: string:

#include <cstdio>
#include <string>

struct Book {
    std::string title;
    int year;
    float price;

    Book(std::string t, int y, float p) {
        title = t;
        year = y;
        price = p;
    }
};

int main() {

    int i;

    Book books[50];
    books[0].title = "Bullshit";
    books[0].year = 132;
    books[0].price = 146.9;

    books[1] = Book(std::string("Money"), 1344, 189.4);

    for (i = 0; i < 2; i++) {
        printf("Book Title is : %s\n", books[i].title.c_str());
        printf("Book Year is %d\n", books[i].year);
        printf("Book price is %3.2f\n", books[i].price);
        printf("\n\n");
    }
}

答案 1 :(得分:0)

这个

books[0].title="Bullshit";

无效。标题定义为char[50]。 <或者

strcpy(books[0].title, "BS");

这会将BS的字节复制到title。或者做

 struct Book
    {
        char *title;
        int year;
        float price;
    };

...
  books[0].title = strdup("BS");

这将标题设置为指向char字符串的指针。 strdup将为字符串分配空间并将BS复制到该空间。你必须释放分配的空间。

或者 - 最好的。使用std :: string

 struct Book
    {
        std::string title;
        int year;
        float price;
    };
....
   books[0].title = "BS";

作为最后的想法 - 使用std :: vector代替原始数组

,生活会更好