C:将数组(指针)传递给函数 [英] C: passing an array (pointer) to a function
问题描述
我有一个函数,我想要一个函数来接收2D数组(H),读取指定的列(col)并将其传递给另一个数组(b)。
如果我希望打印1,则下面的代码似乎不正确。
非常感谢任何指导。
I have a function I would like to have a function to receive a 2D array (H), to read a specified column (col) and to pass it to another array (b). It appears that the code below is not OK has I was expecting to get a 1 printed. Any guidance is very much appreciated.
#define nline 5
#define ncol 4
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
void count0(int **M,int col, int *a);
void main(){
int i;
int **H;
H=(int**)malloc(nline*sizeof(int*));
for(i=0;i<nline;i++){
H[i]=(int*)malloc(ncol*sizeof(int));
}
H[0][0]=8;
H[0][1]=5;
H[0][2]=6;
H[0][3]=0;
H[1][0]=7;
H[1][1]=5;
H[1][2]=4;
H[1][3]=0;
H[2][0]=5;
H[2][1]=1;
H[2][2]=1;
H[2][3]=7;
H[3][0]=0;
H[3][1]=0;
H[3][2]=0;
H[3][3]=2;
H[4][0]=1;
H[4][1]=0;
H[4][2]=1;
H[4][3]=4;
int *b;
int col=1;
count0(H,col,&b);
printf("num 0=%d\n",b[2]); getchar();
}
/////////////////////////////////////////////////////////////////////////////////
void count0(int **M,int col, int *a){
int i;
a=(int*)malloc(1*sizeof(int));
for(i=0;i<nline;i++){
a[i]=M[i][col];
a=realloc(a,(i+2)*sizeof(int));
}
}
推荐答案
As您已经知道count0函数中矩阵中的行数= nline
。因此,您只需要一次在count函数中为数组 a
分配所有内存,而无需调用realloc()函数。
As you already knows the number of rows = nline
in your matrix in count0 function. So you should simply allocate all memory for array a
in count function one time, you don't need to re-call realloc() function.
void count0(int **M, int col, int** a){
(*a) = malloc(nline * sizeof(int));
for(i = 0; i < nline; i++){
(*a)[i] = M[i][col];
}
}
注意:的优先级[ ]
比 *
高,因此您需要()
大约 * a
Note: precedence of []
is higher then *
so you need ()
around *a
只需将此函数调用为: count0(H,col,& b);
just call this function as: count0(H, col, &b);
和 free(b);
在printf语句之后的main()中显式释放内存。
and free(b);
in main() after printf statement to deallocate memory explicitly.
这篇关于C:将数组(指针)传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!