Page 1 of 1

[SOLVED]2D array assignment(C++)

Posted: Sat Feb 27, 2010 1:27 pm
by Donutslayer7
A pretty basic question, I know: when I declare a 2D array...

Code: Select all

int map[5][5] =
{
          {0,0,0,0,0},
          {0,0,0,0,0},
          {0,0,0,0,0},
          {0,0,0,0,0},
          {0,0,0,0,0}
}
the code is fine, when I assign part of an array...

Code: Select all

map[3][2] = 1;
but I want to know if there is a way I can assign all of an arrays values at once much like declaring it...

Code: Select all

map[5][5] = //this doesn't work
{
...
}
I know I can use a for loop to loop through the array, but I just want to know if it's possible to assign it all at once

Re: 2D array assignment(C++)

Posted: Sat Feb 27, 2010 1:33 pm
by Bakkon
I'm about 100% sure there's not a shorthand way to do it and you're required to loop through each element. The only way to assign a value to everything at once is when it's first defined, such as:

Code: Select all

int array[25] = {0};
This will initialize each element to 0, but there's no way to do something like that after it's already defined.

edit: Clarification, if you did this:

Code: Select all

int array[25] = {1};
It will initialize element [0] to 1 and the rest of the elements to 0.

Re: 2D array assignment(C++)

Posted: Sat Feb 27, 2010 2:15 pm
by GroundUpEngine
Bakkon wrote:I'm about 100% sure there's not a shorthand way to do it and you're required to loop through each element.
That's the way I learned too ;)

Code: Select all

-- e.g.

for(int i = 0; i < 5; i++)
{
    for(int j = 0; j < 5; j++)
    {
         map[i][j] = 0;
    }
}

Re: 2D array assignment(C++)

Posted: Sat Feb 27, 2010 2:20 pm
by avansc
calloc

Re: 2D array assignment(C++)

Posted: Sat Feb 27, 2010 2:40 pm
by qpHalcy0n
You probably would not want to calloc. You'd want to memset in this case.

Re: 2D array assignment(C++)

Posted: Sat Feb 27, 2010 2:53 pm
by RyanPridgeon
You could create a seperate array such as

Code: Select all

int preset[3][3] = {
  { 0, 0, 0 },
  { 0, 1, 2 },
  { 1, 1, 2 }
};
or whatever, then use memcpy(), or your own function to copy the preset array into the array you're working with, such as

Code: Select all

int level[3][3];
memcpy(level, preset, sizeof(preset));
Which will copy it to be identical to your preset array, not matter where you are in the code (as long as preset is in scope).

Re: 2D array assignment(C++)

Posted: Sat Feb 27, 2010 6:26 pm
by avansc
^^, yeah if the mem was already allocated, and if you wanted anything other than 0.
but yeah, memset would be better.

Re: 2D array assignment(C++)

Posted: Sat Feb 27, 2010 8:29 pm
by eatcomics
Or you could use a for loop, like the others said... But I guess you can do a memset

Re: 2D array assignment(C++)

Posted: Sun Feb 28, 2010 12:04 am
by Donutslayer7
ah, copying a previous array, great idea, thanks, I'll look into this memset function