0

I have a data file of about 2500 lines. Each line contains 5 parameters. I declare a strut out side of a routine.

typedef struct data
{

char date[9];
char time[3];
float price;
float NAV;
float percent_change;
} _data ;

void readfile(int *j, struct data *input);

void readfile(int *j,struct data *input)

I set aside memory to read each line of the file into an array of structs.

input = calloc(days_of_data,sizeof(*input));
for (i = 0; i< days_of_data; i++)
    input[i] = *(_data*)calloc(1,sizeof(_data));

and read the file.

while(fgets(line, 75, fp) != NULL)
{      

    date = strtok(line,",");
    strcpy(input[i].date,date);
    time = strtok(NULL,",");
    strcpy(input[i].time, time);
    price = strtok(NULL,",");
    input[i].price = atof(price);
    NAV = strtok(NULL,",");
    input[i].NAV = atof(NAV);
    percent_change = strtok(NULL,",");
    input[i].percent_change =  atof(percent_change);
    i--;

}

This works. Now I want to sent the structure to the main program.

int main(int argc, const char * argv[]) {
struct data *input;
readfile(&j, input);
printf("%f\n",input[0].percent_change);
}

This compiles but crashes on the print statement.

1 Answer 1

1

You will have to use return value

struct data * readfile(int *j) {
    struct data *input;
    /* read the data */
    return input;
}

int main(int argc, const char * argv[]) {
    struct data *input;
    input = readfile(&j);
    printf("%f\n",input[0].percent_change);
}

or pointer

void readfile(int *j, struct data **input_out) {
    struct data *input;
    /* read the data */
    *input_out = input;
}

int main(int argc, const char * argv[]) {
    struct data *input;
    readfile(&j, &input);
    printf("%f\n",input[0].percent_change);
}

to pass the data to the caller.

Sign up to request clarification or add additional context in comments.

6 Comments

that is right, or even j=readFile(&input); for int readFile(struct data **input_out)
@milevyo I'm not sure if it is right because I don't know how j (the argument) is used in readfile and how j (a global variable?) is used in main or other parts of the program.
it is an unused variable, it let us just guess that it returns nb items or the sizeof the struct input
I tried both methods. Both ran but printed out 0.000000 which is the wrong value. j is not pertinent to the issue at hand.
This won't be the cause, but input[i] = *(_data*)calloc(1,sizeof(_data)); do cause memory leak. Just don't do it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.