gpt4 book ai didi

c - 二维动态分配数组并将其作为参数传递的问题

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:16 25 4
gpt4 key购买 nike

我有以下问题:我正在填充一个二维数组,其行数是我正在读取的文件数。因此,每行中的列数对应于从文件中读取的数据字节数。

考虑到这张图片,我有以下程序:我必须返回从每个文件读取的数据字节数组和每个文件的大小。这是我的:

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;
}

代码在主函数的“j”循环中出现段错误。有人可以点灯吗?如何做得更好?

谢谢。

最佳答案

您正在按值传递 fileArray,因此在 fillArrays 中,您正在将该指针的副本修改为指针,因此在执行 fillArrays 函数后, main 函数中的 fileArray 不受影响 - 它仍未初始化,您需要通过 reference 传递此变量(传递指向 fileArray 的指针):

fillArrays(&fileArray,fileSize, &noFiles);

然后在 fillArrays 中您需要添加这些修改:

void fillArrays(unsigned char ***array, size_t dataSize[], int *nFiles)
{
//...
*array = (unsigned char**)malloc(nrows * sizeof(unsigned char *));
//...
(*array)[i] = (unsigned char *) malloc(dataSize[i] * sizeof(unsigned char));
///...
(*array)[i][j] = 0x03;
}

关于c - 二维动态分配数组并将其作为参数传递的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52482096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com