c代码中的困惑

标签 c struct pass-by-reference call-by-value

我对这段代码有疑问,为什么我在 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);
}

最佳答案

从技术上讲,C 仅支持按值调用。当数组作为函数参数传递时,它们“退化”为指针。当你传递指针时,你仍然是按值传递它,即指针的值,但是你可以修改指针指向的内容。

传递指针时,您可以将其视为按引用调用,但需要了解实际发生的情况。

关于c代码中的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18316368/

相关文章:

用于双字符串比较的 C case 语句

c - 避免在 C 预处理器中重复替换

c - 如何连续声明结构而不将其设为数组?

c - 从类型 ‘memstruct’ 分配给类型 ‘int’ 时的类型不兼容

c - 将数组从文件 1 中的方法传递到文件 2 中的方法,而不在方法中使用额外参数

Java 通过引用传递问题

c++ - 有没有办法在 C 或 C++ 中嵌入 Sh/Bash session ?

c - 有没有关于如何在 C 中使用 GStreamer GstBaseTransform 的完整示例?

c - 溢出以更改 C 结构中的下一个元素

C++:如何分配和填充通过引用传递的结构的动态数组?