user5987642
user5987642

Reputation:

How does structure array copying work in C?

This is the code that I want to run in 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);
}

The output that I am expecting is: t ri a b

However I am getting: t rib a b

What is it that I am doing wrong?

Upvotes: 0

Views: 82

Answers (3)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

strcpy(student1.name,"ri");//copy "ri" to second struct's name variable

This is definitely wrong. "ri" is actually three characters due to null terminator also. So you are copying three bytes to array which has 2 bytes, thus invoking undefined behaviour with this.

Upvotes: 3

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

In your code, name is an array having two chars. OTOH, the size of "ri" is three characters, including the null-terminator.

So, by saying

  strcpy(student[1].name,"ri");

you're overrunning the memory. This invokes undefined behavior.

From the man page

[...] The strings may not overlap, and the destination string dest must be large enough to receive the copy. [...] If the destination string of a strcpy() is not large enough, then anything might happen.

Once you hit UB, the program behavior cannot be justified.

To be able to hold "ri", you need to change

char name[2];

to

char name[3];

Upvotes: 1

Md. Shohan Hossain
Md. Shohan Hossain

Reputation: 118

#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);
}

Upvotes: 0

Related Questions