jj.
jj.

Reputation: 105

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.

Upvotes: 2

Views: 96

Answers (3)

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

Upvotes: 0

Thaddeus Hughes
Thaddeus Hughes

Reputation: 317

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.

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409176

Because of the operator precedence the expression *devices[i] is parsed as *(devices[i]) which is not quite what you want. You want to use (*devices)[i] instead.

Upvotes: 4

Related Questions