1

I am trying to do the following but am getting the following error:

"error: expected expression before { token

Test_Stubs.h

#define SIGNATURE 0x78,0x9c

Test.c

#include "Test_Stubs.h"

static unsigned myArray[100];

static void
setup(void)
{
    myArray = {SIGNATURE};
}

EDIT

Follow on question:

Is there a way to assign the individual values in the #define to specific indexes of myArray? For instance...

#include "Test_Stubs.h"

static unsigned myArray[100];

static void
setup(void)
{
    myArray[0] = SIGNATURE[0]; //0x78
    myArray[1] = SIGNATURE[1]; //0x9c
}

Clearly the above code will not code as SIGNATURE is neither an array or pointer.

1 Answer 1

5

As per the C syntax rules, you can only initialize an array using a brace enclosed initializer list at the time of definition.

Afterwards, you have to initialize element by element, using a loop, or, if you need to initialize all the elements to the same value, you can consider using memset().


EDIT:

No, as I mentioned in my comments, as per your code snippet, SIGNATURE is neither an array name, nor represent any array type, so you cannot use indexing on that.

However, using compound literal (on and above C99), if you change your #define, then, somehow, you can make this work. See the below code for example,

#include <stdio.h>

#define SIGNATURE ((unsigned [100]){0x78,0x9c})

static unsigned myArray[100];

int main (void)
{
    myArray[0] = SIGNATURE[0]; //0x78
    myArray[1] = SIGNATURE[1]; //0x9c

    return 0;
}

See a LIVE VERSION

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

3 Comments

Thank you. I had a quick follow on question if you don't mind addressing. See edit.
@ILostMySpoon SIGNATURE it not an array type variable, even not an array type after preprocessing stage. So, you cannot use indexing on it.
What would be the best workaround to achieve what I am trying to do?

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.