简体   繁体   中英

3x3 array = 10 numbers

i have this code

#include <math.h>
#include <stdio.h>

const int n = 3;
const int s = 3;
int getm(int mat[n][s]);
int printm(int mat[n][s]);

int main()
{
    int m[n][s];
    getm(m);
    printm(m);
    return 0;
}

int getm(int mat[n][s])
{
    for(int x = 0;x < n;x++)
    {
        for (int y = 0;y<s;y++)
        {
            scanf("%i ", &mat[x][y]);
        }
    }
    return 0;
}
int printm(int mat[n][s])
{
    for(int x = 0;x<n;x++)
    {
        for(int y = 0;y<s;y++)
        {
            printf("%i ", mat[x][y]);
            if(y==(s-1))
            {
                printf("\n");
            }
        }
    }
}

which shoud ask for 9 numbers to make a 3x3 matrix array, but it actually asks for 10 numbers, printm is working well - printing only 9 numbers. Where is error?

I think the problem is the space after %i : you do not need the tenth number, but your code is asking for it anyway, because it waits to get a space after the ninth number.

Separately, your printing code can be optimized a little by dropping the if :

for(int x = 0;x<n;x++)
{
    for(int y = 0;y<s;y++)
    {
        printf("%i ", mat[x][y]);
    }
    printf("\n");
}
scanf("%i ", &mat[x][y]);

摆脱%i后面的空格,因此它只读取一个数字:

scanf("%i", &mat[x][y]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM