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