user3717271
user3717271

Reputation: 57

Returning pointer to statically defined array of structs

I statically defined a myStruct and inside the struct, I have an innerStruct array of size 3. I want to return a pointer to that array so I can assign a local pointer to point to one of the elements in order to modify the values later on.

At one part it seems like my compiler tells me I'm returning an int instead of innerStruct * type.

How do I do it correctly? Is a double pointer necessary?

#include <stdio.h>

typedef struct
{
  int content;

} innerStruct;

typedef struct
{
  int a;
  innerStruct inner[3];

} myStruct;

static myStruct m1;

innerStruct * getMyStructPtr()
{
    return &(m1.inner);
}

int main()
{
    int id = 0;
    int elem = 1;
    /* Define a local ptr so I can modify values of the m1 struct */
    innerStruct * local_ptr = NULL;

    innerStruct * myStruct_ptr = getMyStructPtr(); // seems like my compiler tells me I'm returning an int instead of innerStruct * type

    /* Point to one of the elements */
    local_ptr = &myStruct_ptr[elem];

    local_ptr->content = 123;

    return 0;
}

Link to online code compiler: https://onlinegdb.com/BJNO9lxA-

Upvotes: 1

Views: 85

Answers (2)

Nik
Nik

Reputation: 1870

Think of it this way: in the context that you are using the array, it is actually equivalent to a pointer. For example m1.inner can actually be used as the pointer innerStruct * to the first element in m1.inner[3].

In order to get a pointer to any one of the elements in your m1.inner array, you can do the following when returning from innerStruct * getMyStructPtr().

  1. To get a pointer to the first element: return m1.inner
  2. To get a pointer to the second element: return m1.inner + 1
  3. To get a pointer to the third element: return m1.inner + 2

Of course you should choose to not hardcode + 1, + 2, but rather pass it as a parameter i.e.

innerStruct * getMyStructPtr(int elementNo)//don't forget it is zero based
{
    return m1.inner + elementNo;
}

That being said, there are of course some differences between arrays and pointers. If you're still a bit confused why arrays and pointers are interchangeable in most circumstances, give this answer a read. The author did a very thorough job explaining it.

Upvotes: 3

cisking
cisking

Reputation: 21

The name of an array without brackets is a pointer to the first element in the array. The function should be:

innerStruct* getMyStructPtr()
{
    return myStruct.inner;
}

If you wanted to access a specific element then you would need:

return &myStruct.inner[2];

Upvotes: 2

Related Questions