Home > Blockchain >  Overwriting an existing 2D Array in C
Overwriting an existing 2D Array in C

Time:01-28

I'm currently writing a project in C, and I need to be able to fill a 2D array with information already stored in another 2D array. In a separate C file, I have this array:

int levelOne[][4] = 
{{5,88,128,0},
{153,65,0,0},
{0,144,160,20}}; //First Array

int levelTwo[][4] = 
{{5,88,128,0},
{153,65,0,0},
{0,144,160,20}}; //Second Array

And in my main file, I have this variable which I'd like to fill with the information from both of these arrays at different points in my code. (This isn't exactly what I'm doing, but it's the general gist):

#include "arrayFile.c"
void main()
{
    int arrayContainer[][4] = levelOne;
    while (true)
    {
        func(arrayContainer);
        if(foo)
        {
            arrayContainer = levelTwo;//Switches to the other array if the conditional is met.
        }
    }
}

I know this method doesn't work - you can't overwrite items in arrays after they're instantiated. But is there any way to do something like this? I know I'll most likely need to use pointers to do this instead of completely overwriting the array, however there's not a lot of information on the internet about pointers with multidimensional arrays. In this situation, what's best practice?

Also, I don't know exactly how many arrays of 4 there will be, so I wouldn't be able to use a standard 3D array and just switch between indexes, unless there's a way to make a 3D jagged array that I don't know about.

CodePudding user response:

Given the definitions you show, such as they are, all you need is memcpy(arrayContainer, levelTwo, sizeof LevelTwo);.

You should ensure that arrayContainer has sufficient memory to contain the copied data and that LevelTwo, since it is used as the operand of sizeof, is a designator for the actual array, not a pointer. If it is not, replace sizeof LevelTwo with the size of the array.

If you do not need the actual memory filled with data but simply need a way to refer to the contents of the different arrays, make arrayContainer a pointer instead of an array, as with int (*arrayContainer)[4];. Then you can use arrayContainer = levelOne; or arrayContainer = levelTwo; to change which data it points to.

Also, I don't know exactly how many arrays of 4 there will be, so I wouldn't be able to use a standard 3D array and just switch between indexes, unless there's a way to make a 3D jagged array that I don't know about.

It is entirely possible to have a pointer to dynamically allocated memory which is filled with pointers to arrays of four int, and those pointers can be changed at will.

  •  Tags:  
  • Related