![](/img/trans.png)
[英]Passing an array pointer to a function and then reallocating the array and changing its values in C
[英]Output the values of a matrix by passing its pointer to a function
我正在尝试发送矩阵的指针以用于打印值。 但是,我的以下代码将打印一些长数字,因此我假设它会打印地址! 传递矩阵的指针后如何打印矩阵的值?
#include <stdio.h>
#include <string.h>
#include <math.h>
void printing(int *edge);
void main(){
int N=3;
int i,j;
int *edge[N];
for (i = 0; i < N; i++){
*(edge+i) = (int *)malloc(N * sizeof(int));
}
srand(0);
for(i = 0; i < N; i++){
for(j = 0; j < N; j++){
if(i == j)
*(*(edge+i)+j) = 0;
else
*(*(edge+i)+j) = 1; //rand() % 10;
}
}
printing(edge); // Pass the pointer of the matrix
}
void printing(int *edge){
int i,j;
int N= 3;
for( i = 0; i < N; i++){
for(j = 0; j < N; j++){
printf("%d \t", ((edge+i)+j)); // I think I have to do something in this line.
}
printf("\n");
}
}
printing
的参数类型不正确。 它应该是int *edge[]
。 然后在打印时,使用*(*(edge+i)+j)
,或者更好的是edge[i][j]
。
结果:
void printing(int *edge[]){
int i,j;
int N = 3;
for( i = 0; i < N; i++){
for(j = 0; j < N; j++){
printf("%d \t", edge[i][j]);
}
printf("\n");
}
}
另外,请确保#include <stdlib.h>
,因为malloc
和srand
需要srand
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.