【问题标题】:Function for defining and printing all the elements of a matrix定义和打印矩阵的所有元素的功能
【发布时间】:2015-04-21 20:41:10
【问题描述】:

我正在研究 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;
}

但是当我尝试编译时,我得到以下错误[EDITED]:

|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)) ===|

【问题讨论】:

  • 你在哪里看到这个语法:int matrice[int y][int x]?
  • 无处,我试过了,因为在我的书中没有这种类型的例子,只是简单的算术运算。

标签: c function for-loop matrix nested-loops


【解决方案1】:

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

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

然后修复你的函数调用:

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

那么您需要在def_matrice 和print_matrice 中声明i 和j。

那么def_matrice 和print_matrice 的参数名称为matrice,但函数中使用名称griglia。

【讨论】:

  • 所以 def_matrice 和 print_matrice 将始终在具有相同参数名称的单个矩阵上工作?
  • @Granpasso 您在函数中声明了一个参数名称matrice,但您从不使用它。相反,您使用不在函数范围内的griglia。
  • 我编辑了它,但我仍然不明白为什么它不起作用。
  • @Granpasso 你不应该编辑你的问题并在看到答案时修改它,否则答案对读者来说不再有意义。其次,您仍然有错误,因为您没有解决我在回答中提到的第二点。现在关于您的评论,您的 griglia 数组在 main 中声明,因此它在其他函数中不可见:您在 def_matrice 正文中使用 griglia 不可见。
猜你喜欢
  • 1970-01-01
  • 2019-10-07
  • 2018-12-23
  • 1970-01-01
  • 2014-08-28
  • 2016-11-13
  • 1970-01-01
  • 2015-07-21
  • 2020-10-30
相关资源
最近更新 更多