![](/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.