Jeremy Klein
Jeremy Klein

Reputation: 23

Print double array by looping

So this is puzzling me. I have a two dimensional array and when I loop to print the first pointers array, it does not give me the same correct information, but if I call each specific place it gives me the correct information.

it has a lot of debugging printf

#include <stdio.h>
#include <string.h>

void input_data(char string[2000], int *arr[51]);
double do_math(int *arr);
void print_data(int **arr);
void make_line(int *result, int num, int score, int weight, int late);

int main(){
   char input[2000];
   char line[100];
   int *grade_book[51];

   while(fgets(line, sizeof(line), stdin)){
      printf("input given: %s", line);
      strcat(input, line);
   }

   printf("input = %s", input);
   input_data(input, grade_book);

   print_data(grade_book);


   return(1);
}

void input_data(char input[2000], int *arr[51]){
   int data[4], result[4];
   int stat, penalty, drop_num, total, r, num, score, weight, late;
   char status, t;

   sscanf(input, " %d %d %c %d", &penalty, &drop_num, &status, &total);
   stat = 0;
   if(status == 'Y'){
      stat = 1;
   }
   printf("penalty: %d, drop_num: %d, status: %c, total = %d\n", penalty, drop_num, status, total);
   data[0] = penalty;
   data[1] = drop_num;
   data[2] = stat;
   data[3] = total;
   arr[0] = data;
   printf("%d %d %d %d", arr[0][0], arr[0][1], arr[0][2], arr[0][3]);

   for(r = 1; r < total; r++){
      sscanf(input, " %d %c %d %c %d %c %d", &num, &t,
       &score, &t, &weight, &t, &late);
       make_line(result, num, score, weight, late);
       arr[num] = result;
   }
}

The output is

input given: 10 0 Y
input given: 2
input given: 2, 80, 40, 0
input given: 1, 100, 60, 0
input = 10 0 Y
2
2, 80, 40, 0
1, 100, 60, 0
penalty: 10, drop_num: 0, status: Y, total = 2
10 0 1 2
10 0 1 2
0:10 1:0 2:4196792 3:0 

Clearly in the loop the 3rd call is a pointer, but I have no clue as to which and why it is giving me this output.

Upvotes: 0

Views: 70

Answers (1)

Crowman
Crowman

Reputation: 25918

In input_data(), you have:

int data[4], result[4];

followed by:

arr[0] = data;

and:

arr[num] = result;

Both data and result are automatic arrays, which means they will be destroyed when input_data() returns. So all those pointers you're putting into arr will point to invalid locations once your function returns.

Even if it worked, the way you currently have it written, every element of arr except the first will all end up pointing to the same location, which is probably not want you want, otherwise you could get away with a 2 element array, rather than a 51 element array.

Instead, you should dynamically allocate arrays for your arr elements to point to.

Upvotes: 1

Related Questions