1

I'm using a library that has a typedef struct that contains a few variables and an array. I'm trying to pass a pointer to a variable of this type to another function and assign values into the array.

//typedef in library file
typedef struct
{
    int a;
    int b;
    int arr[5];
} MyType;

... This is in another file

void foo()
{
    MyType newtype;
    //...lots of code

    setArray( &newtype );

return;
}

void setArray ( MyType* mytype )
{
    mytype->arr = {
        1,2,3,4,5,
    };

return;
}

When I try to compile this code I get the following error on the line with

mytpe->arr = {

Expected expression before '{' token

I've tried it a few different ways such as mytype->arr[5] = { but I get various syntax errors.

I'm new to C but I understand that an array really acts as a pointer to the first element in the array. Is what I'm trying to do not possible and I need to loop through the indices of each array and assign them one at a time?

3
  • mytype->arr[0] = 1; mytype->arr[1] = 2; ... Commented Sep 17, 2015 at 13:01
  • So arr has no type? Looks weird. Commented Sep 17, 2015 at 13:13
  • 1
    "an array really acts as a pointer" NO! An array is not a pointer! The name of the array is just converted to a pointer to the first element for most (i.e. not all!) uses. Commented Sep 17, 2015 at 13:13

1 Answer 1

1

You cannot assign to arrays like that. You have to do it element-wise, like:

mytype->arr[0] = 1;
mytype->arr[1] = 2;
...

or using a function like memcpy.

const int values[] = {1, 2, 3, 4};
memcpy(mytype->arr, values, sizeof values);

Better make sure the sizes and types fit.

Note that in an initialization (part of an array declaration and definition), you can set the array in one "step". But this is a different thing.

Sign up to request clarification or add additional context in comments.

Comments

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.