c - 形式论证中如何修改结构变量

标签 c struct

在下面的程序中,当我将结构变量传递给递减函数时,实际参数如何受到影响,如返回无效。我做了类似的其他例子,发现当我将它作为形式参数传递时,结构值没有改变。这个例子怎么是异常..

/*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/

相关文章:

C regex.h 最短匹配

c - 父子进程控制

c++ - MPI_Isend 之后 MPI_Wait 的确切行为是什么?

c - 如何使用结构从文本文件中读取并将其加载到内存中?

c - 纯 C 中的“结构”

c - C 中函数指针如何工作

c++ - 在 C++ 中将 double 转换为 (IEEE 754) 64 位二进制字符串表示形式

c - 如何在 c 中打印结构成员的值(使用指向结构的指针)

c - 为什么不能全局定义结构成员?

c++ - 结构的 QVector - 没有合适的默认构造函数可用