简体   繁体   English

C指针malloc里面的函数调用

[英]C pointers malloc inside function call

I have such hierarchy: 我有这样的等级制度:

main()
{
    int i;
    myStruct *devices = NULL;
    myFunc1(&devices);

    for (i = 0; i < 5; i++)
    {
        printf("MAC: %s, Name: %s, COD: %s\n\r", devices[i].field1, devices[i].field2, devices[i].field3);
    }
}

void myFunc1(myStruct **devices)
{
    myFunc2(devices);
}

void myFunc2(myStruct **devices)
{
    int i;
    *devices = malloc(sizeof(myStruct) * 5);

    for (i = 0; i < 5; i++)
    {
        (*devices[i]).field1 = "test1";
        (*devices[i]).field2 = "test2";
        (*devices[i]).field3 = "test3";
    }
}

At main when I access devices[i] with i = 0, it is ok, but when i > 0 SegFault happens, and I can not understand how to access it correctly. 在主要当我访问i = 0的设备[i]时,它没问题,但是当i> 0时发生SegFault,我无法理解如何正确访问它。

Because of the operator precedence the expression *devices[i] is parsed as *(devices[i]) which is not quite what you want. 由于运算符优先级 ,表达式*devices[i]被解析为*(devices[i]) ,这不是你想要的。 You want to use (*devices)[i] instead. 您想要使用(*devices)[i]

I'm fairly sure 我很确定

(*devices[i])

Should be 应该

((*devices)[i])

Since [] operator takes precedence over the * operator. 由于[]运算符优先于*运算符。 You want to dereference the pointer, and then access the array. 您想要取消引用指针,然后访问该数组。

I think that the problem is that you are calling the wrong structure. 我认为问题在于你正在调用错误的结构。 First of all try to substitute 首先尝试替代

*devices[i]).field1

To

*devices[i])->field1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM