2

I am having problems updating an array globally from a while loop, as expalined below. Please note that I can only use functionality from C 95 and before. Anyhelp would be greatly appreciated! Full paste bin http://pastebin.com/ss6VgTCD

Declared at the Top of my program

int data_count, i;
float *x_values, *y_values;
float x[100],y[100];

In My main function my arrays are created using the code below:

printf("\nPlease Enter How Many Data Points You Wish To Enter: \n");
scanf("%d", &data_count);
x_values=(float*)calloc(data_count,sizeof(*x_values));
y_values=(float*)calloc(data_count,sizeof(*y_values)); 
if (x_values==NULL) {
     printf("Error! Memory Could Not Be Allocated. ");
     exit(0);
}

File read function to import previously entered data, the function is getting the correct data and displays the correct data points in my debugging line printf("%12f%12f\n", x_values[i], y_values[i]); however is only locally updating x_values and y_values as these imported data can not be seen by the rest of the program. How can I globally update the array?

     void file_read(void) {
     store = fopen ("j:/StoredValues.txt", "r");
     if (store == NULL )
              printf("\nError: Failed To Open Previous Data File - Program Will Continue Anyway\n");
     else {
              printf("\nSuccess: Data From Previous Run Imported\n");
              i=0;
              do { 
              fscanf ( store, "%f,%f\n", &x[i], &y[i]);
              x_values = x;
              y_values = y;
              printf("%12f%12f\n", x_values[i], y_values[i]);
              i=i+1;
              } while (!feof(store));
              fclose(store);
     }
}

p.s. Ive only coded in C for 2 weeks so simple is nice :)

Henry Quekett
  • 429
  • 1
  • 7
  • 16
  • There's nothing called C95, assuming you mean C90+AM1 from 1995. Casting the result of calloc was dangerous in C90+AM1, so don't do it. In C99 it is no longer dangerous, just [pointless](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/22538350#22538350). – Lundin May 08 '14 at 14:24

2 Answers2

3

In the first code block you've allocated memory and saved the pointer to it in 'x_values'. In the second block you change 'x_values' to point to the 'x' array. The 'x' array already has memory allocated to it for 100 floating point values.

You will no longer have a pointer to the allocated memory after the assignment. Any data stored there is no longer accessible since you no longer have a pointer to it.

edit:

Here's a suggested replacement for the file_read() routine:

void file_read(void) {
     store = fopen ("j:/StoredValues.txt", "r");
     if (store == NULL )
              printf("\nError: Failed To Open Previous Data File - Program Will Continue Anyway\n");
     else {
            printf("\nSuccess: Data From Previous Run Imported\n");
            float* px;
            float* py;
            px = x_values;
            py = y_values;
            while (!feof(store))
            {
                fscanf ( store, "%f,%f\n", px, py);
                printf("%12f%12f\n", *px, *py );
                px++;
                py++;
            }
              fclose(store);
     }
}

Edit 2:

Menu choice 2 will display the content of x_values. If file_read() places the content in the x array then you can't display it using option 2. You also can't copy the content of the x array to x_values since x_values doesn't exist yet.

You need to create a storage area for your data before you try to read it in. To do that you need to store the count of how many points are in the file.

Also consider:

The user enters 10 points and you allocate space for 10. Then the user wants to enter new data and wants to enter 12. You now have to free() and alloc() to get space for the extra two.

Jay
  • 13,803
  • 4
  • 42
  • 69
  • Thankyou for your response, How would I structure the program better to avoid this ? – Henry Quekett May 08 '14 at 14:31
  • @HenryQuekett You wouldn't be using global variables at all in a properly structured program. Instead, you would pass the arrays as parameters to the function. – Lundin May 08 '14 at 14:32
  • I'm not clear on what you're trying to do but... Since the declaration of the x and y arrays already allocates memory perhaps you can store your data directly in those arrays? (and remove the x_values allocation altogether) – Jay May 08 '14 at 14:34
  • Unfortunatley I cant remove the x_values and y_values alltogether as they are used by the full program here is a pastebin to help put the code in context http://pastebin.com/ss6VgTCD – Henry Quekett May 08 '14 at 14:39
  • I've edited my response with a suggested replacement. You might need to move the declarations for px and py to the top of the function to get your version of C to compile it. This does NOT check for too much input. If your file is larger than you allocate memory for it will crash hard. – Jay May 08 '14 at 14:57
  • I would love to be able to say it worked however when I replaced my function I got crashes just played withit and cant get it to work any differntly thankyou for looking / trying though! – Henry Quekett May 08 '14 at 15:11
  • I ran your code in the debugger. It's crashing because it's calling file_read() at the top of the program before x_values and y_values are allocated. I'll edit the post to clarify it – Jay May 08 '14 at 15:39
  • 1
    Didnt end up using the code but your explanation in part 2 helped me fix the problems I was having thankyou :) – Henry Quekett May 09 '14 at 10:16
2
          x_values = x;
          y_values = y;

This causes x_values and y_values to point at the statically allocated arrays instead of the data you allocated dynamically for them. So after this assignment, the dynamic data now sits alone and isolated in your RAM as a memory leak, with no reference to it from your program.

Lundin
  • 195,001
  • 40
  • 254
  • 396