1
votes

I'm trying to extract the data from a file and store it directly in an array from the fread function. However, it seem like the data type is incorrect?

Here is the error message:

dataPlus.c:28:15: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'void *' [-Werror,-Wint-conversion] fread(ptr[i], 1, 1, in);

How can I make those data accessible? For instance, if I want to check if the first 3 char in the text files are 1, 2, and 3.

/**
 * To store specific lines of data from fread into array.
 * Alternatively, to make the buffer recieved from fread, readible
 **/

#include <stdio.h>

int main(void)
{

FILE* in = fopen("in.txt", "r");

if (in == NULL)
{
    printf("File does not exist.\n");
    return 1;
}


FILE* out = fopen("out.txt", "w");

//read file information into array.
int ptr[4];

//error here... Tried to store it directly into array instead of buffer..
    for(int i = 0; i < 4; i++)
    {
        fread(ptr[i], 1, 1, in);
    }


    for(int j = 0; j < 4; j++)
    {
        printf("success. Array[%i] is --> %i value\n", j, ptr[j]);
    }

fclose(in);
fclose(out);
}
2

2 Answers

1
votes

In C pointers and arrays are quite the same, so int ptr[4]; means that you have an array of 4 integers, and you can access them using the usual notation (e.g. ptr[3] = 2;) or, with pointer arithmetic, *(ptr+3) = 2;, which does the same thing.

The function fread() expects a pointer of some kind, so you have to give it an address, in your case the address of (operator &) the i:th element in the array, like fread(&(ptr[i]), 1, 1, in); or fread(ptr + i, 1, 1, in);

The compiler error says just this, you are giving to the function an integer instead of a pointer.

1
votes

int ptr[4]; is a array of intrigers, so ptr[i] is a intriger.

If you need a array of pointers, this is the way

int *(ptr)[4] so ptr[i] is a pointer.