0

This is a very simple C program. I have a structure Student and I created only 1 structure variable through structure to an array. But no matter what size array I create I am still able to take more inputs through the for loop and it even stores it. Why is it so?

[You can see the screenshot image here-->] https://i.stack.imgur.com/oYupX.png

Here is the code:

#include<stdio.h>

struct Student
{
int rollNo;
char name[10];
int marks;
};

int main()
{
struct Student s[1];
printf("\n--------Enter student details--------\n");

for(int i=0; i<3; i++)
{
    printf("\nStudent %d",i+1);
    printf("\nEnter roll no       : ");
    scanf("%d",&s[i].rollNo);
    printf("Enter name          : ");
    fflush(stdin);
    gets(s[i].name);
    printf("Enter marks         : ");
    scanf("%d",&s[i].marks);
}
printf("\n--------Entered student details are--------\n");
for(int i=0; i<3; i++)
{
    printf("\nStudent %d",i+1);
    printf("\nRoll no       : %d",s[i].rollNo);
    printf("\nEnter name    : %s",s[i].name);
    printf("\nEnter marks   : %d\n",s[i].marks);
}
return 0;
}

Output of the above code:

--------Enter student details--------

Student 1
Enter roll no       : 1
Enter name          : ABC
Enter marks         : 90

Student 2
Enter roll no       : 2
Enter name          : XYZ
Enter marks         : 80

Student 3
Enter roll no       : 3
Enter name          : PQR
Enter marks         : 70

--------Entered student details are--------

Student 1
Roll no       : 1
Enter name    : ABC
Enter marks   : 90

Student 2
Roll no       : 2
Enter name    : ☺
Enter marks   : 80

Student 3
Roll no       : 3
Enter name    : PQR
Enter marks   : 70

And yes there is a smiley in the 2 student output.

Thanks:)

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    It may happen to work but it's undefined behavior to access elements of an array past its declared or allocated size. – sj95126 Oct 05 '21 at 15:53
  • 1
    Also, don't use ```gets()```. Never ever. [See here](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – sj95126 Oct 05 '21 at 15:54
  • Don't post pictures of your code, post code as properly formatted text (which you did BTW). – Jabberwocky Oct 05 '21 at 15:54
  • If I'm accessing an array past its allocated size should I not be getting an error? – Achellis16 Oct 05 '21 at 16:05
  • @Achellis16 no, as per the specification of the C language accessing memory out of bounds is _undefined behaviour_ (google that term). Anything can happen including the program apparently working fine. – Jabberwocky Oct 05 '21 at 16:08

0 Answers0