代码之家  ›  专栏  ›  技术社区  ›  Tristan Ridley

无法通过引用将typedef结构传递给函数

  •  -1
  • Tristan Ridley  · 技术社区  · 7 年前

    我试图通过引用将自定义类型对象传递给函数,但我不知道我可能做错了什么。我读过 How do you pass a typedef struct to a function? 以及其他参考资料,我可以发誓我已经做到了。我清除了所有我正在做的事情,甚至这个斯巴达代码也会抛出5个错误。帮帮我,Stackexchange;你是我唯一的希望!

    目标只是能够更改对象中数组中的值。

    #include <stdio.h>
    #include <math.h>
    typedef struct structure {
        char byte[10];
        char mod;
    } complex;
    void simpleInit (complex *a, char value) {//put the value in the first byte and zero the rest
        a.byte[0] = value;
        char i;
        for (i = 1; i < 10; ++i) {
            a.byte[i] = 0;
        }
        a.mod = 1;
    }
    void main () {
        complex myNumber;
        char value = 6;
        simpleInit (myNumber, value);
    }
    

    当我尝试运行此操作时,会出现以下错误和4个类似错误:

    测试2.c:10:3:错误:请求非结构或联合中的成员字节

    a、 字节【0】=值;

    2 回复  |  直到 5 年前
        1
  •  1
  •   tadman    7 年前

    a 是指针类型,因此需要取消引用才能使用它。通常使用箭头操作符完成此操作:

    a->byte[i] = 0;
    

    由于这只是一个字节数组,您还可以快速将其“归零”:

    memset(a, 0, 10);
    

    尽管考虑到重要性 10 在你的代码中,你应该把它写成常量或 #define .

        2
  •  1
  •   Ernest Collection    7 年前

    通过引用传递值时,需要使用星号访问结构的所有字段,例如:

    (*a).byte[0] = value;
    

    很高兴您做到了->作为快捷方式,这将是:

    a->byte[0] = value;
    

    也不要忘记致电;您呼叫时的接线员(地址) simpleInit .

    #include <stdio.h>
    #include <math.h>
    
    typedef struct structure 
    {
        char byte[10];
        char mod;
    } complex;
    
    void simpleInit (complex *a, char value) 
    {
        char i;
    
        a->byte[0] = value;
    
        for (i = 1; i < 10; ++i) {
            a->byte[i] = 0;
        }
    
        a->mod = 1;
    }
    
    int main() 
    { 
        complex myNumber;
        char value = 6;
        simpleInit (&myNumber, value);
    }