I have the following problem: I am populating a 2D array whose number of rows is the number of files I am reading. Therefore the number of columns in each row corresponds to the bytes of data read from the file.
With this picture in mind I have the following program: I have to return a byte array of data read from each file and the size of each file. This is what I have:
void fillArrays(unsigned char **array, size_t dataSize[], int *nFiles)
{
printf("Calling fillArrays\n");
int i, j, nrows;
nrows = 3;
*nFiles = nrows; // assuming no. of files to be read = 3
dataSize = (size_t *)malloc(nrows * sizeof(size_t));
array = (unsigned char**)malloc(nrows * sizeof(unsigned char *));
dataSize[0] = 4; // assuming file 1 contains 4 bytes
dataSize[1] = 3; // assuming file 2 contains 3 bytes
dataSize[2] = 1;// assuming file 3 contains 1 bytes
//populating file data into a 2D array. Here for test purpose assuming each file has data = 0x03!!
for(i = 0; i < nrows; i++)
{
array[i] = (unsigned char *) malloc(dataSize[i] * sizeof(unsigned char));
for(j = 0; j < dataSize[i]; j++){
printf("round %d %d\n", i,j);
array[i][j] = 0x03;
printf("array [%d][%d] = %02X\n ", i, j , array[i][j]);
}
//array[i][dataSize[i]]= '\0';
}
}
int main(int argc, char *argv[])
{
unsigned char **fileArray;
int noFiles = 0;
size_t *fileSize;
fillArrays(fileArray,fileSize, &noFiles);
printf("Returned no. of files = %d\n", noFiles);
printf("fileSize[0] = %lu\n", fileSize[0]);
printf("fileSize[1] = %lu\n", fileSize[1]);
printf("fileSize[2] = %lu\n", fileSize[2]);
int j = 0;
for (int i = 0; i < noFiles; i++){
printf("i = %d\n", i);
for (int j = 0; j < fileSize[i]; j++){
printf("Obtained data from file %d : (fileArray [%d][%d]) = %02X\n ", i, i, j , fileArray[i][j]);
//j++;
}
}
return 0;
}
the code is segfaulting in the 'j' loop in the main function. Could someone throw some light? How can this be done better?
Thanks.