Home > Software engineering >  Different Outputs From Same Program
Different Outputs From Same Program

Time:03-25

With the following code when compiled with GCC, only three inputs are taken from the user whereas compiled with an online C compiler takes 5 inputs. Why this is happening??

#include <stdio.h>
struct student {
    char firstName[50];
    int roll;
    float marks;
}; 

int main() {
    struct student s[3];
    int i,n;
    //printf("Enter n students:\n");
    //scanf("%d",&n);

    // storing information
    for (i = 1; i <=5;   i) {
        
        printf("Enter first name: ");
        scanf("%s", s[i].firstName);
        printf("Enter marks: ");
        scanf("%f", &s[i].marks);
    }
    printf("Displaying Information:\n\n");

    // displaying information
    for (i = 1; i <=5;   i) {
        
        printf("First name: %s\n",s[i].firstName);
        
        printf("Marks: %.f", s[i].marks);
        
    }
    return 0;
}

CodePudding user response:

You're writing past the bounds of the array s. It only has 3 element, but you're attempting to write to 5. Writing past the end of an array triggers undefined behavior, which in your case manifested as different behavior on two different systems.

Change s to have 5 elements.

struct student s[5];

You're also looping from 1 to 5 in both your read and write loops. The first element of an array has index 0, so you want to loop from 0 to 4.

for (i = 0; i <5;   i) {
  • Related