Global arrays

Mar 15, 2013 at 10:59pm
I currently have globally declared arrays, which are accessed by multiple functions.
I want to turn the program so that the arrays are no longer globally declared, but are passed to functions by reference.

I have one problem with passing the arrays:
I found that, through debugging, I HAVE TO resize the array when I pass it by reference. For instance, I was using int a[10] when it was globally declared, when it is passed by reference with size 10, it does not work, instead it should be higher than 10 (certain number).
Why is this happening?
I do not get it...
Mar 15, 2013 at 11:21pm
closed account (Dy7SLyTq)
use std::vector
Mar 15, 2013 at 11:40pm
closed account (zb0S216C)
Arrays simply do not change in size because they can't. If you know the exact size of the array, then it's recommended that you pass the array by reference, and not a pointer to the first element of the target array. For instance:

1
2
3
4
5
6
// Avoid this:
void Function( int *Array_ );

// Prefer this:
size_t const Array_Length_( 10 );
void Function( int( &Array_ )[Array_Length_] );

The difference between the two function prototypes is that the first function prototype accepts the address of any arbitrary "int", whereas the second function prototype accepts only the address of an array with n elements of type "T".

Wazzak
Mar 16, 2013 at 12:07am
I know the size of the array.
By resize i meant, for global arrays If i used int a[10],
When I want to pass int a[10] by reference, like the way you stated, it does not work.
But instead if I use a[100], then it starts to work..
Mar 16, 2013 at 9:31pm
I think you're not passing it correctly, please post an excerpt of your code.
Mar 16, 2013 at 10:29pm
closed account (zb0S216C)
qwepoi123 wrote:
"it does not work. But instead if I use a[100], then it starts to work.."

The length of an array simply cannot change. Full stop. Therefore, no matter what you do, you will never be able to change the array's length. What you need is a resizeable array, namely "std::vector":

http://www.cplusplus.com/reference/vector/vector/

Wazzak
Last edited on Mar 16, 2013 at 10:30pm
Mar 17, 2013 at 1:29am
I don't think he wants to be able to resize it. It's the fact that for whatever reason when he passes the array into the function it doesn't work if it's put in the way he is putting it in. I think an example of the code you're using that isn't working would be helpful, if possible.
Last edited on Mar 17, 2013 at 1:48am
Topic archived. No new replies allowed.