Single massive array cell dynamically allocated behaving as an array with multiple smaller cells

41 views Asked by At

I am having some strange behavior that when i wrote the code thought was normal behavior.

In my code i allocate memory for a one cell array of the same size as the file. I then try to access this array using image[i] as if it were an array with multiple cells.

What i don't understand is why does this work? If i used int instead of char, would it behave similarly but with half or less of the "cells"?

char *testImage = "testdata/TestPng.png";
char *image;
int c;
long fSize = 0;
long i = 0;
FILE *fp;

// open image
fp = fopen(testImage, "rb");

// find file size
fseek(fp, 0l, SEEK_END);
fSize = ftell(fp);
rewind(fp);

// allocate memory
image = calloc(1, fSize*sizeof(char))

// read from file and store in image buffer
while( ( c = fget(fp) ) != EOF ) {
    image[i] = (char) c;
    i++;
}

/*
Usage of the image buffer and later clean up
.
.
.
*/
0

There are 0 answers