0

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

3 Answers3

3

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.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
  • So what can I do? Should I just increase the size of the name variable in my struct from name[2] to name[3] for it to work in this case? –  Feb 27 '16 at 19:33
  • @rohitkrishna094 Yes it will work in this case if you increase to 3. But maybe you need larger array – Giorgi Moniava Feb 27 '16 at 19:33
  • 1
    Oh doing so, it worked. Thanks a lot for your prompt help. I knew about null character but forgot about it when I was writing this code. Thanks. –  Feb 27 '16 at 19:34
1

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];
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
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);
}