first row in my pointer array printing is broken and not sure why

Viewed 33

Basically trying to print from a data file using a structure. Not sure why but the output for the first row goes crazy. Also, yes i know theres huge mem leak right now I need to do stuff with the data before i can purge it

CSCE1040 �U, PU: -1214516224, 21942, -1214517008 Cummings, Kelley: 74, 70, 79 Reynolds, Jamie: 64, 52, 66 ...

#include <stdio.h>
#include <stdlib.h>
#include "student.h"
#include "bubble.h"
#include <string.h>
#include <assert.h>

student ***studentDataBase;

struct classStats
{
  char* name;
  float mean;
  float min;
  float max;
  float median;
};

void printStudent(student *studentData) //print student data
{
printf("%s, %s: %d, %d, %d\n", 
        studentData->last,
        studentData->first,
        studentData->exam1,
        studentData->exam2,
        studentData->exam3);
}

void printData(student *students[], int studentcount) 
//for each student call printStudent
{
  int i;
  for(i=0;i<studentcount;i++)
      printStudent(students[i]);
}

int main()
{
  int studentcount = 19;
  //classStats classStats;
  char className[10];
  char tempFirst[50];
  char tempLast[50];

  scanf("%s", className); 
//get and print class name to skip first line
  printf("%10s\n", className);

  studentDataBase = (student***) malloc (studentcount*sizeof(student**)); 
//allocate mem for #students rows
  for(int i=0; i<studentcount;i++)
  {
    studentDataBase[i] = (student**) malloc(6*sizeof(student*));
//allocate mem for 6 columns
    for(int j=0;j<6;j++)
    studentDataBase[i][j] = NULL;
  }

  for(int i=0;i<studentcount;i++) 

  {
    studentDataBase[0][i] = (student*)malloc(sizeof(student));
//allocate mem for data in each column
    scanf("%s %s %d %d %d" //fill in student data
          ,tempFirst, tempLast
          ,&studentDataBase[0][i]->exam1, &studentDataBase[0][i]->exam2, 
&studentDataBase[0][i]->exam3);
    //allocate space for student name
    studentDataBase[0][i]->first = (char*)malloc(strlen(tempFirst)+1); //allocate mem for 
char array
    strcpy(studentDataBase[0][i]->first, tempFirst);
    studentDataBase[0][i]->last = (char*)malloc(strlen(tempLast)+1);
    strcpy(studentDataBase[0][i]->last, tempLast);

    for(int j=1;j<studentcount;j++)
//copy current student data to all student data
    studentDataBase[j][i] = studentDataBase[0][i];
  }

  printData(*studentDataBase,studentcount);

  free(studentDataBase);

  return 0;
}
1 Answers

Mistake in the end,

 for(int j=1;j<studentcount;j++)
//copy current student data to all student data
    studentDataBase[j][i] = studentDataBase[0][i];

I was copying over the 19 pointers to the array which houses 6 pointers.

for(int j=1;j<6;j++)
    //copy current student data to all student data
        studentDataBase[j][i] = studentDataBase[0][i];

Should look like this because basically in my code, 'i' represents the rows of data, and 'j' represents the columns of data.

Related