gpt4 book ai didi

c - 如何确定二维数组的大小?

转载 作者:行者123 更新时间:2023-11-30 19:09:09 26 4
gpt4 key购买 nike

我正在尝试找到一种方法来查找二维数组的大小。这是我用来创建矩阵的函数:

float** createMatrix(int rows, int colums,char populate){

float** matrix = malloc(sizeof(float*)*rows); // allocates the memory for all the pointers of the 2D array

for(int i = 0;i<rows;i++){ // allocates the memory for each pointer in the 2D array
matrix[i] = malloc(sizeof(float)*colums); // allocates the memory for all the colums in each row
}

if(populate=='Y'){
for(int i = 0;i<rows;i++){ // prompts the user for values to create the array
for(int j = 0;j<colums;j++){
printf("Value for row %d colum %d: ",i+1,j+1);
scanf("%f",&matrix[i][j]);
}
}

}else if(populate=='N'){
return matrix;
}

return matrix; // returns the matrix created
}

测试一下:

float** matrix = createMatrix(100,100,'N');  

int rows = sizeof(matrix)/sizeof(float*);
int colums = sizeof(matrix[0])/sizeof(float) - 1;

printf("Rows: %d and Cols: %d",rows,colums);

我得到“行:1 和列:1”作为输出。我不确定我做错了什么?

最佳答案

答案就在函数调用中的参数值中:

    createMatrix(100,100,'N')

所以答案应该是 100 行和 100 列。

变量矩阵是第[0][0]个索引矩阵的内存地址,它是一个二维数组。从这个内存地址,无法使用 sizeof() C 函数找出 2D 的维度。可能有一种方法可以逻辑地回溯它。

以下是您获得上述输出的原因:

   int rows = sizeof(matrix)/sizeof(float*);
int colums = sizeof(matrix[0])/sizeof(float) - 1;

matrix 是一个浮点型双指针。浮点型双指针的大小为 8。Matrix[0] 是一个指向 float 的指针。指向 float 的单个指针的大小为 8。sizeof float 为 4。(大多数情况)

所以我们有

    sizeof(matrix)/sizeof(float *) = 1    //since 8/8 = 1.
sizeof(matrix[0])/sizeof(float) = 2 //since 8/4 = 2

关于c - 如何确定二维数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43692076/

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