在下面的程序中,当我将结构变量传递给递减函数时,实际参数如何受到影响,如返回无效。我做了类似的其他例子,发现当我将它作为形式参数传递时,结构值没有改变。这个例子怎么是异常..
/*P11.11 Program to understand how an array of structures is sent to a function*/
#include<stdio.h>
struct student
{
char name[20];
int rollno;
int marks;
};
void display(struct student);
void dec_marks(struct student stuarr[], int a);
int main(void)
{
int i,a=5;
struct student stuarr[3]={
{"Mary",12,98},
{"John",11,97},
{"Tom",13,89}
};
dec_marks(stuarr,a);
for(i=0; i<3; i++)
display(stuarr[i]);
printf("%d",a);
return 0;
}
void dec_marks(struct student stuarr[], int a)
{
int i;
a=a+4;
for(i=0; i<3; i++)
stuarr[i].marks = stuarr[i].marks-10;
}
void display(struct student stu)
{
printf("Name - %s\t", stu.name);
printf("Rollno - %d\t", stu.rollno);
printf("Marks - %d\n", stu.marks);
}
最佳答案
这个例子不同,因为它不传递要修改的结构,它传递的是这样一个结构的数组:
void dec_marks(struct student stuarr[], int a)
// ^^^^^^^^
// Array
数组作为一个地址传递给它们的初始元素,相当于传递一个指针;不需要 &
运算符。另一方面,整数变量 a
是按值传递的,因此函数内的 a = a+4
赋值对 main
没有影响>.
如果您重组程序以采用单独的 struct
并将循环移动到 main
中,则它为 display(struct student stu)< 完成的方式
调用然后你的程序将停止工作,正如预期的那样。
// This does not work
void dec_marks(struct student stu) {
stu.marks -= 10;
}
...
for(i=0; i<3; i++)
dec_marks(stuarr[i]);
关于c - 形式论证中如何修改结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988299/