【问题标题】:incompatible pointer to integer conversion assigning to char from char[13] [duplicate]指向从 char [13] 分配给 char 的整数转换的不兼容指针 [重复]
【发布时间】:2020-12-19 06:38:31
【问题描述】:

我创建了一个学生结构,当我将名称分配给结构内定义的字符数组时,它给了我一个错误“指向整数转换的不兼容指针,将 char 分配给 char [13] ....任何人都可以解释我为什么会这样?

int main()
{
    typedef union {
        int roll_no;
        char name[30];
    } student;
    student student1;
    student1.roll_no = 5;
    student1.name[30] =
        "shivam kumar"; // this is line where it is giving me error
    printf("\n%d", student1.roll_no);
    printf("\n%s", student1.name);

    return 0;
}

【问题讨论】:

  • OT:typedef union 嗯...确定要union?我假设您需要 struct 而不是 union

标签: arrays c string char structure


【解决方案1】:

在 C 中你不能这样复制字符串:

    student1.name[30] =
        "shivam kumar"; // this is line where it is giving me error

改为使用strcpy:

student student1 = {0};
student1.roll_no = 5;
strcpy(student1.name, "shivam kumar");  //<--

最好使用strncpy确保目标缓冲区没有溢出:

 strncpy(student1.name, "shivam kumar", sizeof(student1.name));
 student1.name[sizeof(student1.name) - 1] = '\0';   // make sure it's NUL-terminated.

【讨论】:

  • 我还要解释需要在复制之前检查字符串的长度以确保没有溢出。
  • @DavidC.Rankin 同意,我根据您的评论添加了一条注释。使用 strcpy 确实有点痛苦。
  • 也许最好提及strncpy,因为它与strlcpy不同,它是C标准的一部分?
  • @r3musn0x 确实
  • 好交易,我犹豫是否使用strncpy(),不是因为它是错误的,只是因为NOTES 部分在他们认为的字符串为空终止时让一些新用户感到惊讶——不是:)man 3 strncpy。只要牢记笔记,就可以达到目的。我通常只做size_t len = strlen(the_string); 然后if (len &gt;= sizeof student.name) { /* handle the error */ } 使用union 而不是struct 也有点奇怪——这将是下一个Q 来...
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2011-04-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2011-07-14
  • 1970-01-01
相关资源
最近更新 更多