user3857017
user3857017

Reputation: 275

File input and pointers to arrays in C

I am trying to scan in a list of data from a text file, and that data is supposed to be put into an array of type double, and this must be done in a function outside of main. Therefore the pointer needs to be to the array in main, from the function actually scanning the data into the array.

The problem comes when I attempt to make the function return the array through a pointer like (assuming the prototype is already existing):

#include <stdio.h>
#include <stdlib.h>

#define SIZE 12    

int
main(void)
{
double data[SIZE];
int i;

readData(data, SIZE);
}



void
readData(double data[], int SIZE)
{
    FILE* fp;
    fp = fopen("data.txt", "r");
    int i;

    for (i = 0; i < SIZE; i++)
    {
        fscanf(read, "%lf", &data[i]);
        if(data[i] < 0)
            printf("Negative data at %d\n", i);
    }

    printf("The array is: ");
    for (i = 0; i < SIZE; i++)
    {
        printf("%f ", data[i]);
    }
fclose(fp);

    return;
}

This simply gives me a run time error and crashes, with no compile error at all. I'm guessing it's due to the fact that the fscanf is attempting to write to &*data[CONST] but I have no idea how else to get it to write to the pointer, and not just a local variable.

Is there some trick to getting file input into a function pointer?

Upvotes: 0

Views: 2086

Answers (3)

mandar
mandar

Reputation: 98

make sure data.txt file exist,

also for demo data.txt should have 12 lines of numbers,

also use file pointer fscanf(fp, "%lf", &data[i]);

Upvotes: 0

m_duran
m_duran

Reputation: 1

You declared int i twice, once in main() and once if your function, but it is unused in main().

When you pass an array to a function, writing to an element of the array is not writing to a local variable because when you pass an array, you are passing a pointer to the first element of the array. When you pass data, it is the same as passing &data[0]. Writing to data[i] is the same as writing to *(data + i), and since data is the address of the first element of your array, you are writing to the array itself, not a copy of it. Similarly, &data[i] gives the address of the i'th element of your original array, not a copy of it, so you can and should use that in your function.

And finally, you are still missing the data type of your array in your function declaration.

In your updated code, you did #define SIZE 12, but later used size. Since C is case sensitive, size and SIZE are not the same.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

You need a little tweak to readData.

void readData(double data[], int CONST);

In main, call

readData(data, CONST);

Also, change the line

    fscanf(read, "%lf", &*data[i]);

to

    fscanf(read, "%lf", &data[i]);

Update

In the updated code, you have

void readData(data[], int CONST)

instead of

void readData(double data[], int CONST)

Upvotes: 1

Related Questions