1

このコードでは、readMat() で指定した値が実際に a と b に格納されるのはなぜでしょうか??

つまり、これは参照ではなく値による呼び出しではありませんか?

ああ、私が間違っていることが他にあれば教えてください。感謝いたします。

事前にサンクス。

#include<stdio.h>

struct spMat
{
    int rowNo;
    int colNo;
    int value;
}a[20],b[20],c[20],d[20],e[20];

void readMat(struct spMat x[20])
{
    printf("Enter the number of rows in the sparse matrix\n");
    scanf("%d",&x[0].rowNo);
    printf("\nEnter the number of columns in the sparse matrix\n");
    scanf("%d",&x[0].colNo);
    printf("\nEnter the number of non-zero elements in the sparse matrix\n");
    scanf("%d",&x[0].value);

    int r=x[0].rowNo;
    int c=x[0].colNo;
    int nz=x[0].value;
    int i=1;

    while(i<=nz)
    {
        printf("\nEnter the row number of element number %d\n",i);
        scanf("%d",&x[i].rowNo);
        printf("\nEnter the column number of element number %d\n",i);
        scanf("%d",&x[i].colNo);
        printf("\nEnter the value of the element number %d\n",i);
        scanf("%d",&x[i].value);
        i++;
    }
}

void printMat(struct spMat x[20])
{
    int k=1,i,j;

    for(i=0;i<x[0].rowNo;i++)
    {
        for(j=0;j<x[0].colNo;j++)
        {
            if((k<=x[0].value)&&(x[k].rowNo==i)&&(x[k].colNo==j))
            {
                printf("%d\t",x[k].value);
                k++;
            }

            else
                printf("%d\t",0);
        }

        printf("\n");
    }
}

void fastTranspose(struct spMat x[20])
{

}

void addMat(struct spMat x[20], struct spMat y[20])
{

}

void multMat(struct spMat x[20], struct spMat y[20])
{

}

void main()
{
    readMat(a);
    readMat(b);
    printMat(a);
    printMat(b);
}
4

3 に答える 3

4

技術的には、C は値渡しのみをサポートしています。配列が関数の引数として渡されると、配列はポインターに "分解" されます。また、ポインターを渡すときは、値、つまりポインターの値で渡しますが、ポインターが指すものを変更できます。

ポインターを渡すときに参照渡しのように考えることができますが、実際に何が起こったのかを理解する必要があります。

于 2013-08-19T14:37:16.973 に答える
2

はい、参照渡しです。C では、関数を次のように宣言したかのように、配列は最初の要素のアドレスを渡すことによって関数に渡されます。

void readMat(struct spMat *x);
于 2013-08-19T14:33:50.613 に答える