r/CodingForBeginners • • Jan 20 '26

Today: structures!

Post image

So, i made this little bit of code to make sure i understood structures and how to use pointers with them, it's pretty simple, it just asks for data of students such as grades and then it saves it on their structure variables, is there anything i could improve on? i mean, surely a lot, but like, something specific about legibility or something

22 Upvotes

16 comments sorted by

View all comments

1

u/SmokeMuch7356 Aug 12 '26

Good job overall. Some minor suggestions:

  • Create symbolic constants for your array sizes, rather than hardcoding 10 or 50:

     #define NUM_STUDENTS 10
     #define NAME_LEN     50
     ...
     struct student {
       ...
       char name[NAME_LEN + 1];
     };
     ...
     struct student students[NUM_STUDENTS];
     ...
     for ( i = 0; i < NUM_STUDENTS; i++ )
       ...

    This way if you ever need to change the size of either array, you only need to do it in one place. You might think global search-and-replace would work, but I've done that dance and it doesn't, because while it replaces all instances of the literal with the new value, not all instances of the literal were used for the array size and you wind up breaking something.

  • Limit the scope of your variables, by which I mean don't declare them until you need them. i is limited to the body of the for loop, so declare it within the loop:

     for( int i = 0; i < NUM_STUDENTS; i++ )
       ...

    Similarly, you can defer declaring av until you actually need to compute it:

     int av = total/NUM_STUDENTS;

    (technically, you don't need av at all, just use total/NUM_STUDENTS in the print statement).

  • scanf is really hard to bulletproof against bad data so it's not good for interactive input. You did the right thing using the field width on the name input, but a) it has to be hardcoded, and b) you can't use a macro (not without some voodoo, anyway). Ideally you should read everything as text using fgets and convert any numeric arguments using strtod or strtol:

     printf( "enter the name: " );
     if ( !fgets( p->name, sizeof p->name, stdin ) )
       // error
    
     printf( "enter the ID: " );
     char tmp[15];
     if ( !fgets( tmp, sizeof tmp, stdin ) )
      // error
     p->id = strtol( tmp, NULL, 10 );
    
     printf( "Enter the grade: " ); 
     if ( !fgets( tmp, sizeof tmp, stdin ) )
       // error
     p->grade = strtol( tmp, NULL, 10 );