简体   繁体   中英

Two different outputs of the same array

I have a question about some odd behaviour with my program. I have two arrays data and ind_array . Both arrays are initialized in main function. ind_array is filled with some values and data is filled with values using function loadData() .

But output of the program depends on where I print values of data array. Before inputting values to ind_array or after.

Look at the first tree numbers of output.

Thanks in advance.

Code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>

#define FILE_NAME "DataValues.csv"
#define NUM_ROWS 40
#define NUM_COLUMS 2
#define COMA " ,"

void loadData(double (*data)[2]){

  //double data[NUM_ROWS][NUM_COLUMS];
  FILE* data_file = fopen(FILE_NAME, "r");
  char line[NUM_ROWS];
  int i = 0;

  while(fgets(line, sizeof(line), data_file)){
    char* tok = strtok(line, COMA);
    int j = 0;
    while(tok != NULL){

        char *ptr;
        data[i][j] = atof(tok);   //const char to double
        tok = strtok(NULL, COMA);

        j++;
      }
      i++;
  }
} 

int main(){
    double data[NUM_ROWS][NUM_COLUMS];
    double ind_array[0][5];
    loadData(data);
    for(int j = 0; j < NUM_ROWS; j++){
        printf(" %f\n", data[j][0]);
    }
    printf("\n");
    ind_array[0][0] = 2;
    ind_array[0][1] =  5;
    ind_array[0][2] =  0;
    ind_array[0][3] =  3;
    ind_array[0][4] =  0;
    for(int j = 0; j < NUM_ROWS; j++){
        printf(" %f\n", data[j][0]);
    }
return 0;
}

Output

 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000 7.000000 8.000000
 9.000000 10.000000 11.000000 12.000000 13.000000 14.000000 15.000000
 16.000000 17.000000 18.000000 19.000000 20.000000 21.000000 22.000000
 23.000000 24.00000025.000000 26.000000 27.000000 28.000000 29.000000
 30.000000 31.000000 32.000000 33.000000 34.000000 35.000000 36.000000
 37.000000 38.000000 39.000000 40.000000

 2.000000 0.000000 0.000000 4.000000 5.000000 6.000000 7.000000
 8.000000 9.000000 10.000000 11.000000 12.000000 13.000000 14.000000
 15.000000 16.000000 17.000000 18.000000 19.000000 20.000000 21.000000
 22.000000 23.000000 24.000000 25.000000 26.000000 27.000000 28.000000
 29.000000 30.000000 31.000000 32.000000 33.000000 34.000000 35.000000
 36.000000 37.000000 38.000000 39.000000 40.000000

Well you are declaring a 0 X 5 array on this line:

double ind_array[0][5];

The total amount of cells in that array is 0 x 5 = 0 . You are printing uninitialized memory which is undefined behaviour, switch the 0 for 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM