c - 传递 2 个未知大小的矩阵作为参数

标签 c function matrix signature declare

首先 - 我的代码有效:

void main(){
int mat1[5][5]={{1,2,3,4,5},
                {6,2,5,5,6},
                {1,5,6,6,7},
                {4,5,6,7,8},
                {5,6,7,8,9}};
int mat2[3][3]={{1,2,3},
                {2,3,4},
                {3,4,5}};
    int mat1size=5,mat2size=3,maxsize=MAX(mat1size,mat2size),*ptr,arraysize=0;
    ptr=func(mat1,mat2,maxsize,&arraysize);
    .
    .
    .
    }


int* func(int mat1[][5],int mat2[][3],int maxsize,int* arraysize){
int i,j,*ptr=(int*)malloc(sizeof(int)*3);
    if(fptr==NULL){
    printf("Out of memory!");
    return;
    }
for(i=0;i<maxsize;i++)
    for(j=0;j<maxsize;j++)
        if(mat1[i][j]==mat2[i][j]){
            if(*arraysize%3==0 && *arraysize!=0)
                ptr=(int*)realloc(ptr,sizeof(int)*(*arraysize+3));
            ptr[*arraysize]=i;
            ptr[*arraysize+1]=j;
            ptr[*arraysize+2]=mat1[i][j];
            *arraysize+=3;
        }
return ptr;
}

问题是我在函数的签名中声明了矩阵列。我正在寻找更通用的解决方案。 如果您想知道该函数应该执行以下操作: 它检查两个矩阵上的每个公共(public)索引。如果值相等 - 将行、列和值添加到新数组并返回它。

最佳答案

使用可变长度数组作为函数参数(这是 100% 标准 C99):

#include <stdio.h>

void print_matrix(size_t w, size_t h, int m[w][h])
{
    for (size_t i = 0; i < w; i++) {
        for (size_t j = 0; j < h; j++) {
            printf("%3d ", m[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int arr[2][3] = {
        { 1, 2, 3 },
        { 4, 5, 6 }
    };

    print_matrix(2, 3, arr);
    return 0;
}

关于c - 传递 2 个未知大小的矩阵作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20254685/

相关文章:

java - 在Java中对二维数组中的列进行就地反转的方法

matlab - 对行求和,但删除每行中的不同项

c - fscanf 导致段错误

c - 如何使用回调修改 GtkWidget 数组的元素

sql - 如何在 SQL 中创建带有 2 个参数的函数?

javascript - 将 JS foreach 传递给 JS post 而不使用表单

r - 在函数内写入大型矩阵 - 快与慢

c - 在数组中找到一对偶数,并将它们的平均值插入到它们之间

c - 使用关键字 'struct' 声明结构对象并在 malloc 中

function - Lua 给全局变量赋值