【问题标题】:why can't i assign to structure parameters? (c) [closed]为什么我不能分配给结构参数? (c) [关闭]
【发布时间】:2014-01-09 09:49:03
【问题描述】:
#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 

我怎么能直接任命,我错在哪里?

【问题讨论】:

  • 33 个整数的数组存储一年?面向未来的设计;)
  • 如果我使用 char *name[15]; 有什么区别?字符 *作者[33];而不是字符名称[15];字符作者[33];
  • 请格式化您提交的代码。

标签: c types structure variable-assignment


【解决方案1】:

你做了什么:

// 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");

【讨论】:

  • 为什么一年不做数组?
  • 真正的问题是:为什么是这样?
  • 是的,你是对的,不需要它:)
【解决方案2】:

您不能将一种类型的值分配给定义为不同类型的变量。在您的示例中,您尝试将单个整数 1986 分配给由 33 个 int 变量组成的数组。

您的其他错误解释起来稍微微妙一些。在 C 中,"a string" 的值的类型为char *,与char[] 的类型不同,因此赋值无效。虽然它们大致相同,但属性略有不同——请阅读char 指针和char 数组在处理字符串时的区别。

【讨论】:

    【解决方案3】:

    此代码存在多个问题。一个问题是您将 'year' 声明为 33 个整数的数组。您可能需要int year; 而不是int year[33];,除非出于某种原因,您要保留与每本书相关的 33 个不同年份的列表。这解释了第一个错误。

    第二个和第三个赋值(作者和年份)的问题是你对 C 中的数组和指针之间的区别感到困惑。(有时指针和数组的名称在 C 中可以互换使用,但并非总是如此,这对于新的 C 程序员来说是一个持续不断的挫折源,因为它不能立即直观地说明为什么有些用法是错误的而另一些是安全的。)网上有很多参考资料比我能更好地解释这一点。这是一个:http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c/

    编译器通过给你特殊的语法来初始化字符数组来帮助这种混淆并没有帮助。当你声明一个字符数组时,像这样:

    char c[33]="JackLondon";
    

    编译器将为 c 保留 33 个字节,然后将“JackLondon”的字节复制到数组的开头,或多或少就像你声明了数组一样,然后用 strcpy() 初始化它。

    在您的具体情况下,您想要的是使用strcpy(或者,最好是strncpy)来加载您的结构,如下所示:

    strncpy(books[0].author, "JackLondon", sizeof(books[0].author));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 2012-08-24
      • 2016-12-22
      • 2014-05-30
      • 1970-01-01
      • 2021-12-27
      • 2022-01-23
      相关资源
      最近更新 更多