Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何读取函数中的二维数组?_C_Arrays - Fatal编程技术网

C 如何读取函数中的二维数组?

C 如何读取函数中的二维数组?,c,arrays,C,Arrays,我有这段代码,如何使用函数读取二维数组? 我写了这个函数,它可以读取所有的数字,但是当我输出到控制台数组时,没有我输入的值 前 输入: 2 1 2 3 4 输出: 16 256 14525376 #include <stdio.h> #include <stdlib.h> void citMat(int a, int n) { int i,j; for(i=1;i<=n;i++) for(j=1;j<=n;j++)

我有这段代码,如何使用函数读取二维数组? 我写了这个函数,它可以读取所有的数字,但是当我输出到控制台数组时,没有我输入的值

前 输入: 2 1 2 3 4 输出: 16 256 14525376

#include <stdio.h>
#include <stdlib.h>

void citMat(int a, int n) {

    int i,j;
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
        {
             printf("a[%d][%d]",i,j);
            scanf("%d", &a);
        }
}

int main()
{   int i,j;
    int a[10][10],n;
    printf("Introdu n:");
    scanf("%d", &n);

    citMat(a[10][10],n);

    for(i=1;i<=n;i++){
        for(j=1;j<=n;j++)
            printf("%d ",a[i][j]);
        printf("\n");
    }
    return 0;
}
#包括
#包括
无效citMat(内部a,内部n){
int i,j;

如果要将
2-d
数组传递给函数,请将函数定义更改为-

2.然后在函数内部
citMat
获取输入-

 scanf("%d", &a[i][j]);    // you need to write like this 
注意-

1。数组索引从
0
开始,因此如果您有一个数组
a[n]
,那么它的有效索引从
0到n-1

因此,从
0
开始读取,直到
n
在所有
for
循环中。如果包含
n
,则访问索引将超出范围,写入索引将导致未定义的行为

所以,要注意这一点


2.
intmain()
->
intmain(void)
intmain(intargc,char**argv)
您只需更改程序中的一些内容即可使其正常工作

1) 使用数组的基址调用函数,如

citMat(a,n);

2) 将函数定义更改为

void citMat(int a[10][10], int n)
使其接受二维数组作为参数


3) 将
scanf()
更改为读取每个元素

scanf("%d", &a[i][j]);

4) 由于数组索引从
0
开始,因此将
循环的所有
终止条件更改为

for(i=1;i<n;i++)

for(i=1;i您需要将原型更改为(此处数组维度很重要)

其他更改由其他人解释(整个代码如下)

#包括
#包括
无效citMat(内部a[10][10],内部n){
int i,j;

对于(i=0;iYou应该阅读有关将数组作为函数参数发送的内容。@Alex上述程序中有许多错误。请重新学习C基础知识,避免直接跳到数组。一个程序中的两种缩进类型。对于:
void citMat(int a[][],int n),我收到了此编译器错误“error:array type具有不完整的元素类型|”
数组中的内部维度缺失,无法编译。代码有很多错误。如果用户在第一次扫描时输入的值与10不同,则程序会显示未定义的行为。回答的目的是解释“如何将2D数组传递给函数”。不过,指出代码中的其他问题仍然很好。我将编辑答案以修复通过scanf读取的无效值。
for(i=1;i<n;i++)
void citMat(int a[10][10], int n)
#include <stdio.h>
#include <stdlib.h>

void citMat(int a[10][10], int n) {

    int i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
    {
        printf("a[%d][%d]:",i,j);
        fflush(stdout);
        scanf("%d", &a[i][j]);
    }
}
int main()
{   int i,j;
    int a[10][10],n;
    printf("Introdu n:");
    scanf("%d", &n);
    if (n > 10)
    {
        fprintf(stderr, "Invalid input %d\n", n);
        return 1;
    }

    citMat(a,n);

    for(i=0;i<n;i++){
        for(j=0;j<n;j++)
        printf("%d ",a[i][j]);
        printf("\n");
    }
    return 0;
}