Passing pointer to function - C programming

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thangviet
    New Member
    • Sep 2007
    • 2

    #1

    Passing pointer to function - C programming

    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:
    Code:
    File contains 1800 lines altogether
    0.00000000               -314.18      -304.77
    1.0000e-04	-423.69	-297.31
    0.00020000	-259.91	-289.69
    ...
    ...
    
    // (d) readData function
    void readData(simData *data)
    {
    //open file coding
    FILE *file_data;
    int k;
    
    if ((file_data = fopen("dissipate.dat", "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
    }
    else
    {	 	 	 	 
    while((fscanf(file_data, "%f %f %f", &data->time[k], &data->dhdt[k], &data->drate[k]))== 3);
    
    }
    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
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You haven't shown your memory allocation which is the most likely cause of the error, however it should be something like
    [code=c]
    data->time = (float *)malloc(sizeof (float) * data->points);
    [/code]to get an array of the correct size.

    Comment

    • thangviet
      New Member
      • Sep 2007
      • 2

      #3
      Thanks for your reply, I'll try that and get back to you on it.

      Comment

      Working...