0

I am trying to change the elements of a C-style array. Using an NSArray/NSMutableArray is not an option for me.

My code is as so:

int losingPositionsX[] = {0, 4, 8...};

but when I enter this code

losingPositionsX = {8, 16, 24};

to change the arrays elements of he array it has an error of: "expected expression" How can I make the copy?

3 Answers 3

1

In C (and by extension, in Objective C) you cannot assign C arrays to each other like that. You copy C arrays with memcpy, like this:

int losingPositionsX[] = {0, 4, 8};
memcpy(losingPositionsX, (int[3]){8, 16, 24}, sizeof(losingPositionsX));

Important: this solution requires that the sizes of the two arrays be equal.

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

2 Comments

The sizes of the arrays will probably not be equal, could I put: sizeof(someNumber) with someNumber being a different size than losingPositionsX?
@RedBadger sizeof(someNumber) would give you wrong results. If you want to copy someNumber of integers, use sizeof(int)*someNumber.
1

You have to use something like memcpy() or a loop.

#define ARRAY_SIZE 3
const int VALUES[ARRAY_SIZE] = {8, 16, 24};

for (int i = 0; i < ARRAY_SIZE; i++)
    losingPositionsX[i] = VALUES[i];

Alternatively, with memcpy(),

// Assuming VALUES has same type and size as losingPositions
memcpy(losingPositionsX, VALUES, sizeof(VALUES));
// Same thing
memcpy(losingPositionsX, VALUES, sizeof(losingPositionsX));
// Same thing (but don't use this one)
memcpy(losingPositionsX, VALUES, sizeof(int) * 3);

Since you are on OS X, which supports C99, you can use compound literals:

memcpy(losingPositionsX, (int[3]){8, 16, 24}, sizeof(losingPositionsX));

The loop is the safest, and will probably be optimized into the same machine code as memcpy() by the compiler. It's relatively easy to make typos with memcpy().

Comments

1

I do not know, whether it is a help for you in relation to memory management. But you can do

int * losingPositionsX = (int[]){ 0, 4, 8 };
losingPositionsX = (int[]){ 8, 16,  32 };

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.