# two array questions

• 04-05-2006
|Wiz|
two array questions
Is there a way to set all the elements of an array to a certain number, say 1, without doing something like

Code:

`hello[] = (1, 1, 1, 1, 1, 1, 1, 1, 1...)`
?

Currently I'm using (for a 3 by 3 array)

Code:

```int cx = 0; int cy = 0; while (cy != 3) { array[cx][cy] = 1; if (cx == 2) { cx = 1; cy++; } else { cx++; } }```
and it's terribly bulky.

Also, if you want to pass an array to a function, do you do something like

Code:

```int main() { int *ptr; ptr = array; function(ptr); ... int function(int ptr)```
or just

Code:

```int main() { function(array) ... function(int *array)```
?
• 04-05-2006
ChaosEngine
Quote:

Originally Posted by |Wiz|
Is there a way to set all the elements of an array to a certain number, say 1, without doing something like

Code:

`hello[] = (1, 1, 1, 1, 1, 1, 1, 1, 1...)`

there's no way to initialise them to 1 without doing that, but you can set them using memset

Code:

`memset(hello, 1, sizeof(hello));`
Quote:

Originally Posted by |Wiz|
Also, if you want to pass an array to a function, do you do something like

Code:

```int main() { function(array) ... function(int *array)```
?

yes. do the second one.
• 04-05-2006
JaWiB
Quote:

there's no way to initialise them to 1 without doing that, but you can set them using memset
Only if he wants to set each byte to 1. If, for example, he wants to set each element of an integer array to one memset won't work properly.
• 04-05-2006
ChaosEngine
Quote:

Originally Posted by JaWiB
Only if he wants to set each byte to 1. If, for example, he wants to set each element of an integer array to one memset won't work properly.

very true. In that case ye olde for loop comes to the rescue...
• 04-05-2006
Daved
You should be using vector (or tr1::array), which happens to have a constructor that does that for you:
Code:

```// Single array with 'size' values std::vector<int> hello(size, 1); // 3x3 array std::vector<std::vector<int> > array(3, std::vector<int>(3, 1));```