By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,810 Members | 1,601 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,810 IT Pros & Developers. It's quick & easy.

Passing pointer to function - C programming

P: 2
Hey guys,
I have a function which needs to read a file and use the pointer parameter given.
the pointer is a structure with five members; int points, float *time, *dhdt, *drate and *diff.
The .dat file contains double values in three columns. I am required to open the .dat file, read the values and insert them into their appropriate members
(1st column of data into *time, 2nd column into *dhdt and 3rd column into *drate).
I have already dynamically allocated memory into the above members.
(data->time = (float *)malloc(sizeof(float), etc);
The variable "points" inside the structure is a user input which is used as the number of lines to read from the file
Here is my code:
Expand|Select|Wrap|Line Numbers
  1. File contains 1800 lines altogether
  2. 0.00000000               -314.18      -304.77
  3. 1.0000e-04    -423.69    -297.31
  4. 0.00020000    -259.91    -289.69
  5. ...
  6. ...
  8. // (d) readData function
  9. void readData(simData *data)
  10. {
  11. //open file coding
  12. FILE *file_data;
  13. int k;
  15. if ((file_data = fopen("dissipate.dat", "r"))==NULL) {
  16. printf("Cannot open file.\n");
  17. exit(1);
  18. }
  19. else
  20. {                    
  21. while((fscanf(file_data, "%f %f %f", &data->time[k], &data->dhdt[k], &data->drate[k]))== 3);
  23. }
  24. fclose(file_data);
how would you get the value of the 1st column to go into the time array?
I tried using a for loop to count through data->points times and print the values line by line but my program crashes.
Any help is much appreciated
Sep 24 '07 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,916
You haven't shown your memory allocation which is the most likely cause of the error, however it should be something like
Expand|Select|Wrap|Line Numbers
  1. data->time = (float *)malloc(sizeof(float) * data->points);
to get an array of the correct size.
Sep 24 '07 #2

P: 2
Thanks for your reply, I'll try that and get back to you on it.
Sep 24 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.