【问题标题】:Function with reference not compiling [duplicate]参考函数未编译[重复]
【发布时间】:2019-04-21 20:35:17
【问题描述】:

我有这个简单的 C 代码,但是在写入和读取函数中包含引用变量输入参数会使程序无法编译。如果我删除&,程序就可以了。我在 Microsoft Visual Studio 2017 上运行它。

#include <stdio.h> 
#include <stdint.h>


typedef struct Cr Cr;
typedef struct Modulation_format_cnfg Modulation_format_cnfg;

struct Modulation_format_cnfg {
    union {
        struct
        {
            uint32_t sc0 : 3;
            uint32_t : 5;
            uint32_t sc1 : 3;
            uint32_t : 5;
            uint32_t sc2 : 3;
            uint32_t : 5;
            uint32_t sc3 : 3;
            uint32_t : 5;
        };
        uint32_t raw;
    };
};

struct Cr
{
    uint32_t const kBlock_base_addr;

    Modulation_format_cnfg volatile modulation_format_cnfg;
};


void write(volatile Modulation_format_cnfg& r, const int val) {
    r.raw = val;
}

uint32_t read(Modulation_format_cnfg volatile& r, const int val) {
    return r.raw;
}

Cr cr[2];

有人可以帮忙吗?

提前致谢!

【问题讨论】:

  • C 没有内置引用; Modulation_format_cnfg volatile&amp; r 不是 C 中的有效参数声明。
  • &amp;,用于声明变量/参数以表示“引用”是 C++ 事物,而不是 C 事物。在 C 语言中,您必须使用 * 来表示“地址”,但如果我没记错的话,会有一些差异。

标签: c


【解决方案1】:

这 (volatile Modulation_format_cnfg&amp; r) 至少是问题之一。在 c 中,您必须通过地址传递(而不是像在 c++ 中那样直接通过引用传递)。为此,可以将该行更改为volatile Modulation_format_cnfg* r,向其传递一个指针(&amp;someStackVarmalloced 堆内存),然后在函数中使用箭头运算符。

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 2015-06-10
    • 2014-07-25
    • 1970-01-01
    • 2023-03-13
    • 2022-10-15
    相关资源
    最近更新 更多