c - 用于定义和打印矩阵的所有元素的函数

标签 c function for-loop matrix nested-loops

我正在研究 C 语言中的函数,我想创建一个函数来将矩阵的所有元素设置为相同的值,然后使用另一个函数打印矩阵。是否可以?这是我写的代码[编辑]:

#include <stdio.h>
#include <stdlib.h>
#define x 79
#define y 24

int def_matrice(int matrice[y][x], int valore);
int print_matrice(int matrice[y][x]);

int main()
{
    int  i = 0, j = 0, matrice[y][x];

    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            matrice[i][j] = 32;
        }
    }

    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            printf("%c", matrice[i][j]);
        }
        printf("\n");
    }

    def_matrice(matrice[y][x], 89);
    print_matrice(matrice[y][x]);

    return 0;
}

int def_matrice(int matrice[y][x], int valore)
{
    int i = 0, j = 0;
    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            matrice[i][j] = valore;
        }
    }
    return 0;
}

int print_matrice(int matrice[y][x])
{
    int i = 0, j = 0;
    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            printf("%c", matrice[i][j]);
        }
        printf("\n");
    }
    return 0;
}

但是当我尝试编译时,出现以下错误[已编辑]:

|30|error: passing argument 1 of 'def_matrice' makes pointer from integer without a cast|
|6|note: expected 'int (*)[79]' but argument is of type 'int'|
|31|error: passing argument 1 of 'print_matrice' makes pointer from integer without a cast|
|7|note: expected 'int (*)[79]' but argument is of type 'int'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

最佳答案

修复原型(prototype)(在函数声明和函数定义处):

int def_matrice(int matrice[y][x], int valore)
int print_matrice(int matrice[y][x])

然后修复您的函数调用:

def_matrice(griglia, 89);
print_matrice(griglia);

然后,您需要在 def_matriceprint_matrice 中声明 ij

然后 def_matriceprint_matrice 的参数名称为 matrice,但在函数中使用名称 griglia

关于c - 用于定义和打印矩阵的所有元素的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29782708/

相关文章:

list - 如何使用 sml 编写函数将 2 元组列表转换为扁平列表?

java - For循环从ArrayList中获取数据

c - 一种 O(n) 时间复杂度的算法,用于在数组中找到彼此之间差异最接近的一对 nos

javascript - 如果键与数组值匹配,如何获取值

java - 如何通过NAT通过公网IP发送UDP数据包?

C++ - 关于函数模板实例化的规则

python - 打印全名python的第一个字母

r - 如何避免复杂的 for 循环?

php - 寻找一个钟形曲线公式来呈现在一个范围内具有零到完全影响的数据

c# - 如何在 C# 中传递指向整数的指针