Reputation:
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
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
Reputation: 134336
In your code, name
is an array having two char
s. 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 astrcpy()
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
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