我创建了一个具有随机值 (0-9) 的连续数组,但我不知道如何将它传递给打印它的函数。
现在我只是在 main 函数中遍历数组,每当我需要打印它时。但我想要一个函数,它会让我的代码更干净。
下面是一个最小的代码示例:
#include <stdio.h>
#include <stdlib.h>
int **alloc_2d_int(int rows, int cols);
int main(int argc, char** argv){
int **matrix;
int i,j,size=3;
matrix = alloc_2d_int(size,size);
// generate the array
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
matrix[i][j] = rand() % 10;
}
}
// how I print the array right now
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
printf("[%d][%d]=%d\n", i,j,matrix[i][j]);
}
}
// this is how I want the printing to happen
print_arr(matrix,3);
}
int **alloc_2d_int(int rows, int cols) {
int *data = (int *)malloc(rows*cols*sizeof(int));
int **array= (int **)malloc(rows*sizeof(int*));
int i;
for (i=0; i<rows; i++)
array[i] = &(data[cols*i]);
return array;
}
void print_arr(int **array,int size)
{
int i,j;
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
printf("matrix[%d][%d]=%d\n", i,j,array[i][j]);
}
}
}
错误信息: “print_arr”的冲突类型[默认启用]
最佳答案
您忘记添加函数的声明(原型(prototype))。在C语言中,默认情况下,函数的返回类型是int
类型。但是对于您的 print_arr()
函数,返回类型是 void
。因此,您会收到冲突类型错误。
因此,在 main()
函数之上声明 print_arr()
函数。喜欢:
void print_arr(int **array,int size);
关于c - 如何在 C 中将连续数组作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44324461/