我无法将多维变量数组传递给C中的一个函数,使用malloc() [英] I am having trouble passing a multidimensional variable array to a function in C using malloc()
本文介绍了我无法将多维变量数组传递给C中的一个函数,使用malloc()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个代码应该在main中创建一个数组,然后打印它,但每次运行它,我只需要得到一个全部0的数组
this code should create an array in main and then print it but every time I run it I just get an array of all 0s
#include <stdio.h>
#include <stdlib.h>
void print(float **A, int w, int h){
int i, j;
A = (float*) malloc(w*h*sizeof(float));
for (i=0;i<h;i++){
A[i] = (float*) malloc(w*sizeof(float));
}
for (i=0; i<h; i++){
for(j=0; j<w; j++){
printf("%f ", A[i][j]);
}
printf("\n");
}
}
int main(void) {
int i;
int x_dimension=3;
int y_dimension=2;
float arr [3][2]={};
arr[0][0]=16.2;
print(arr,x_dimension,y_dimension);
return 0;
}
推荐答案
你正在重新在打印
函数中,这应该可以工作:
You're re-allocing it in your print
function, this should work:
#include <stdio.h>
#include <stdlib.h>
void print(float * A,int h, int w){
int i,j;
for (i=0;i<h;i++){
for(j=0;j<w;j++){
printf("%f ",A[i * w + j]);
}
printf("\n");
}
}
int main(void) {
int i;
const int x_dimension=3;
const int y_dimension=2;
float arr[x_dimension][y_dimension];
arr[0][0]=16.2;
print(arr,x_dimension,y_dimension);
return 0;
}
请注意,我也将 w
和 h
print
中的参数。
Note that I also inverted the w
and h
parameters in the print
function.
这篇关于我无法将多维变量数组传递给C中的一个函数,使用malloc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文