ram*_*rur 5 c arrays function gcc4.7
我有一个假设将2D数组作为参数的函数,我的代码看起来像这样 -
#include <stdio.h>
#include <stdlib.h>
void func(double**, int);
int main()
{
double m[3][3] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
func(m, 3);
}
void func(double **m, int dim)
{
int i, j ;
for(i = 0 ; i < dim ; i++)
{
for(j = 0 ; j < dim ; j++)
printf("%0.2f ", m[i][j]);
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
然后编译器说 -
test.c: In function ‘main’:
test.c:9:2: warning: passing argument 1 of ‘func’ from incompatible pointer type [enabled by default]
func(m, 3);
^
test.c:4:6: note: expected ‘double **’ but argument is of type ‘double (*)[3]’
void func(double**, int);
^
Run Code Online (Sandbox Code Playgroud)
但是当我说 -
int main()
{
int i, j;
double m[3][3] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}};
double **m1 ;
m1 = (double**)malloc(sizeof(double*) * 3);
for(i = 0 ; i < 3 ; i++)
{
m1[i] = (double*)malloc(sizeof(double) * 3);
for(j = 0 ; j < 3 ; j++)
m1[i][j] = m[i][j] ;
}
func(m1, 3);
for(i = 0 ; i < 3 ; i++) free(m1[i]);
free(m1);
}
Run Code Online (Sandbox Code Playgroud)
它编译并运行.
我有什么办法可以func()
同时采用静态/动态定义的2D阵列吗?我很困惑,因为我传递指针m
,为什么第一种情况不正确?
这是否意味着我需要为两种不同类型的参数编写两个单独的函数?
您对2d数组的动态分配不正确.用它作为:
double (*m1)[3] = malloc(sizeof(double[3][3]));
Run Code Online (Sandbox Code Playgroud)
然后它会工作.
而且将函数原型更改为:
void func(double m[][3], int dim)
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用大小的1-D阵列w * h
而不是2-D阵列.
从@TheParamagneticCroissant c99的评论开始,您也可以使用VLA并使您的维度变量.(你需要正确分配2D数组)
将功能签名更改为:
void func(int dim, double[dim][dim]); /* Second arg is VLA whose dimension is first arg */
/* dim argument must come before the array argument */
Run Code Online (Sandbox Code Playgroud)