gpt4 book ai didi

c - 为什么我不能分配结构参数? (C)

转载 作者:行者123 更新时间:2023-11-30 20:15:17 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

struct BOOK{
char name[15];
char author[33];
int year[33];
};

struct BOOK *books;
int main(){
int i,noBooks;
noBooks=2;
books=malloc(sizeof(struct BOOK)*noBooks);
books[0].year=1986;
books[0].author="JackLondon";
books[0].name='MartinEden';

getch();
return 0;
}

我的代码就是这样。当我使用scanf时它有效,但我不能像那样直接指定。

错误是:

error: incompatible types when assigning to type 'int[33]' from type 'int'|
error: incompatible types when assigning to type 'char[33]' from type 'char *'|
error: incompatible types when assigning to type 'char[15]' from type 'int'|
Build finished: 3 errors, 1 warnings

如何直接指定,我哪里错了?

最佳答案

你做了什么:

// assign a numeric value to an array
int year[33];
books[0].year=1986;

// assign a pointer to a memory location of an array
char name[15];
char author[33];
books[0].author="JackLondon";
books[0].name='MartinEden';

它应该是什么样子

struct BOOK{
char name[15];
char author[33];
int year;
};

// ==============================

// assign numeric value to a normal int variable
books[0].year=1986;
// copy values to arrays
strcpy(books[0].author, "JackLondon");
strcpy(books[0].name, "MartinEden");

关于c - 为什么我不能分配结构参数? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20705203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com