0

How can I assign a pointer to an array in c? As in this example, I want to some.x has values stored in vals

typedef struct s
{
    int x[];
}s;

int main()
{   
    int* vals = malloc(sizeof(int) * 10);
    for (int i = 0; i < 10; i++)
        vals[i] = i + 10;

    s some;
    //some.x = vals?

    return 0;
}
3
  • 7
    You can't assign anything to an array. Commented Jun 11, 2018 at 16:32
  • 1
    take a look here: c-faq.com/aryptr/index.html Commented Jun 11, 2018 at 16:35
  • 1
    @yano thanks - very interesting Commented Jun 11, 2018 at 16:41

3 Answers 3

4

Assuming you want to allocate a structure with a flexible array member, and not assign a pointer to an array (which as others have stated - you can't do that)

To use a flexible array member, you need to allocate the structure plus an amount of memory for the array.

typedef struct s
{
    int x[];
}s;

int main()
{   
    s *some = malloc( sizeof( *some ) + ( 10 * sizeof( int ) ) );
    for ( int i = 0; i < 10; i++ )
        some->x[i] = i + 10;

    return 0;
}

Note that you can not leave the sizeof( struct ... ) out of the allocation - the structure's presence is not guaranteed to be zero, even when the flexible array member is the only field in the structure.

As @chux noted in the comments, this would be more consistent with using variables instead of types as sizeof() arguments:

    s *some = malloc( sizeof( *some ) + ( 10 * sizeof( some->x[0] ) ) );
Sign up to request clarification or add additional context in comments.

1 Comment

For consistency of sizeof(variable) vs. sizeof (type), could use malloc( sizeof *some + 10*sizeof some->x[0] );
1

Arrays are not pointers, thats all.

Comments

1

You cannot do what you want. It is outside of the C11 standard n1570.

Arrays do decay into pointers, but not the other way round. You cannot assign to an array.

So use systematically pointers.

And your code cannot have any sense: think of the sizeof involved data!

Read about flexible array members. You'll use pointers to a struct containing them.

1 Comment

hm, I just want to create the _SCATTER_GATHER_LIST structure from MSDN: learn.microsoft.com/en-us/windows-hardware/drivers/ddi/content/… and I don't know how to assign elements to SCATTER_GATHER_ELEMENT Elements[]; field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.