SiteBanner

Since the 'C' structure construct is so kewl <ahem>, what could be better than being able to establish ARRAYS of structures?  Well, coding a 2D array of structures.  Any time more than a few multi-element data groups are needed, maybe this data format will help your program's design.

 

(right-click to download)

/* pgm27 source */

#include <stdio.h>

#define MAXROW 3
#define MAXCOL 2

enum {RET_ERR = -1, RET_OK};

struct motorcycles {          // POSITIONS of STRUCT elements has NO relation to how they are displayed
     char name[25];             // meaning, below, we print the order SIZE, WEIGHT then NAME
     int size;
     float weight;
     };

int main(void) {
     int c;                 // VOODOO 'scanf()' fix
     int entrycount;
     int row;
     int col;
     struct motorcycles mc[MAXROW][MAXCOL];

     printf("\nPlease enter %d lines.\n", MAXROW * MAXCOL);
     printf("Each line: Motorcycle length MC weight MC name \n\n");

     entrycount = 0;
     for (row = 0; row < MAXROW; row++) {
          for (col = 0; col < MAXCOL; col++)   {
                printf("Entry %d: ", ++entrycount);
                scanf("%d %f %[^\n]", &mc[row][col].size, &mc[row][col].weight, mc[row][col].name);

                while ((c = getchar()) != '\n' && c != EOF );          // VOODOO code for 'scanf()' fix
                }
           }

     printf("\nResults:\n\n");
     for (row = 0; row < MAXROW; row++)   {
          for (col = 0; col < MAXCOL; col++)
               printf("mc[%d][%d].size: %d .weight: %.2f .name: %s\n", row, col, mc[row][col].size, mc[row][col].weight, mc[row][col].name);
          }

     printf("\n\n");
     for (row = 0; row < MAXROW; row++)  {
          for (col = 0; col < MAXCOL; col++)
               printf("Address of mc[%d][%d] -- %p\n", row, col, &mc[row][col]);
          }

     printf("\n");
     return(RET_OK);
     }