The array does not print the correct values

I am trying to read numbers from a text file and store it in an array. When I try to read the numbers in the array, the output is insignificant. This is my code:

struct point{ double x[7]; double y[7]; }point; int main() { FILE *fp; fp = fopen("data_2.txt", "r"); struct point points; int len = 8; int i = 0; int j = 0; int k = 0; double a = 0; double b = 0; double c = 0; double total = 0; int left=0; int right=0; int line = 0; for (i=0;i<len;i++) { fscanf(fp, "%lf %lf", &points.x[i],&points.y[i]); } for(i = 0; i < len;i++) printf("looking at point %.2f %.2f\n",points.x[i],points.y[i]); return(0); } 

The test file used contains the following numbers

  2.3 7.5 7.6 7.1 8.5 3.0 5.9 0.7 1.0 2.0 5.1 5.8 4.0 4.5 4.3 3.4 

The output I get is this:

 looking at point 2.30 4.30 looking at point 7.60 7.10 looking at point 8.50 3.00 looking at point 5.90 0.70 looking at point 1.00 2.00 looking at point 5.10 5.80 looking at point 4.00 4.50 looking at point 4.30 3.40 

What am I doing wrong?

+6
source share
2 answers

The problem is that your structure is not large enough to hold 8 numbers and causes undefined behavior . You have double x[7] , but you go to 8.

Why you get this particular behavior, and I can reproduce it here on OS X, I'm not sure. But this behavior is undefined for you.

+7
source

Update your structure as follows:

 struct point{ double x[8]; double y[8]; }point; 

This will help you read and display the data correctly. example-with-stdin

+3
source

Source: https://habr.com/ru/post/1014910/


All Articles