如何在C中通过引用传递结构? [英] How to pass structure by reference in C?

查看:54
本文介绍了如何在C中通过引用传递结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构,需要用于两个不同的变量(firstVar 和 secondVar).我不想使用 vector ,只是 2 个普通结构.因为我不想复制接受用户输入的代码,所以我想创建一个我为 (firstVar 和 secondVar) 调用的操作

I have a structure that I need to use for two diferent variables (firstVar & secondVar). I don't want to use vectors , just 2 plain structures. Since I don't want to duplicate the code that takes the user input, I would like to create an action that I call both for (firstVar and secondVar)

我希望能够通过引用将结构传递给操作.这是我的代码,我仍然无法弄清楚我做错了什么.

I would like to be able to pass the structure to the action by reference. Here is my code, I still can not figure out what I am doing wrong.

#include <stdio.h>
typedef struct {
    int id;
    float length;
} tMystruct;
tMystruct firstVar;
tMystruct secondVar;

void readStructs(tMystruct *theVar)
{
    scanf("%d",theVar.id);
    scanf("%f",theVar.length);
}

int main(void)
{
    readStructs(&firstVar);
    readStructs(&secondVar);
    return 0;
}

推荐答案

问题来了,

void readStructs(tMystruct *theVar)
{
scanf("%d",theVar.id); //<------problem 
scanf("%f",theVar.length); //<------problem 
}

您应该使用 -> 运算符访问 Structure 指针成员,并且您还缺少 & 最终会导致分段错误.

You should access Structure pointer member using -> operator and also you're missing & that will eventually cause a segmentation fault.

这是修改后的代码,

void readStructs(tMystruct *theVar)
{
scanf("%d",&theVar->id);
scanf("%f",&theVar->length);
}

这篇关于如何在C中通过引用传递结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆