结构数组复制如何在C中工作?

时间:2016-02-27 19:27:03

标签: c arrays structure strcpy

这是我想在C中运行的代码。

#include<stdio.h>
#include<string.h>
main()
{
    struct record {
        char name[2];
        char letter;
    };

    struct record student[10];
    strcpy(student[0].name,"t");//copy "t" to first struct's name variable
    strcpy(student[1].name,"ri");//copy "ri" to second struct's name variable
    student[0].letter='a';//copy "a" to first struct's letter variable
    student[1].letter='b';//copy "b" to second struct's letter variable
    printf("%s %s %c %c", student[0].name, student[1].name, student[0].letter, student[1].letter);
}

我期待的输出是:t ri a b

但是我得到了:t rib a b

我做错了什么?

3 个答案:

答案 0 :(得分:3)

  

strcpy(学生1。name,“ri”); //将“ri”复制到第二个结构的名称   变量

这绝对是错误的。由于null终止符,"ri"实际上是三个字符。因此,您将三个字节复制到具有2个字节的数组,从而使用此方法调用undefined behaviour

答案 1 :(得分:1)

在您的代码中,name是一个包含两个char的数组。 OTOH,"ri"的大小是三个字符,包括空终止符。

所以,说

  strcpy(student[1].name,"ri");
你正在超越记忆。这会调用undefined behavior

来自man page

  

[...]字符串可能不重叠,目标字符串dest必须足够大才能接收副本。 [...]如果strcpy()的目标字符串不够大,则可能发生任何事情。

一旦你点击UB,程序行为就不合理了。

为了能够容纳"ri",您需要更改

char name[2];

char name[3];

答案 2 :(得分:0)

#include<stdio.h>
#include<string.h>
main()
{
    struct record {
        char name[3];
        char letter;
    };

    struct record student[10];
    strcpy(student[0].name,"t");//copy "t" to first struct's name variable
    strcpy(student[1].name,"ri");//copy "ri" to second struct's name variable
    student[0].letter='a';//copy "a" to first struct's letter variable
    student[1].letter='b';//copy "b" to second struct's letter variable
    printf("%s %s %c %c",student[0].name,student[1].name,student[0].letter,student[1].letter);
}