6

One of my apps that I'm working on at the moment relies on a multi-dimensional array. So far, I've been using a static array that was defined once, in a style similar to:

float exampleArray[2][2] = {{1, 2},
                            {3, 4}};

However, I'd now like to redefine this array, and such arrays cannot be easily redefined. Unlike when I initialised the array, I'd have to redefine every element of this array separately, for example:

exampleArray[1][1] = 3;
exampleArray[1][2] = 0.5;
exampleArray[2][1] = 17;
exampleArray[2][2] = 2;

Since I'm working on a 17x17 array, the idea of having to do this doesn't really appeal to me! (And I don't really want to keep each array in memory at once, so three arrays or a three-dimensional array isn't the right way to go about this)

I've looked into using a dynamic array instead. Theoretically, using a dynamic array, even I couldn't change everything in one go, I could free the memory for the old array, and then allocate memory for the new array.

However, I've not seen a way of defining a dynamic array in the style of the first example. Is there any easy way to define (or redefine) a dynamic array without directly manipulating one element at a time (i.e. in a similar fashion to my first example)?

EDIT: See the suggestions below for methods that doesn't require dynamic arrays. Thanks for the quick responses!

2
  • 3
    Define an other array and switch the pointers ? Commented Nov 17, 2013 at 15:08
  • 1
    Use some for loops to get each element? Commented Nov 17, 2013 at 15:10

1 Answer 1

8

You can always copy one array to another using memcpy:

float exampleArray[2][2] = {{1, 2},
                            {3, 4}};

float newArray[2][2] = {{ 3, 0.5},
                        {17, 2}};

memcpy(exampleArray, newArray, sizeof(exampleArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Great suggestion! Thanks for the incredibly fast responses!

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.