initialising arrays

How do you set all the entries in an array to 0 or a particular number...

much appreciated
To set to zero

const size_t N = 10;

int a[N] = {}; // C++ code

or

int a[N] = { 0 }; // C code

To set to a value

const size_t N = 10;

int a[N];
int value = 10;

std::fill( a, a + N, value ); // C++ code

or

for ( int *p = a; p != a + N; ++p ) *p = value; // C code
thanx that really helped
Misc. other stuff:

- For char arrays, you can also use

1
2
3
const size_t N = 10;

char a[N] = "";


(I favour this form when zeroing char buffers, as I think of them as string holders.)

- if you need to reset a array to zero in C++, you can (of course) use std::fill() (with a value of 0).

- an alternative way of zeroing an array in C is memset
http://www.cplusplus.com/reference/cstring/memset/

Where a is an array that has been defined (and used) previously

- if a is defined like int a[N]; (on the stack, an evil global, ...)

memset(a, 0, sizeof(a));

- if it's allocated on the heap, e.g. int* a = new int[a_size];

memset(a, 0, a_size * sizeof(int));

Memset is quite popular so you are bound to bump into code using it. And for most modern compilers, it is an intrinsic function provided by the compiler (that is, the compiler doesn't link to a library, it injects the required machine code directly into your program).

- if you want to zero an array allocated on the heap at the point it's allocated, you can use value initialization.

int* a = new int[size](); // this array is zeroed

The brackets () must be empty: if can only be used to zero the array, not set it to a value. In C++11, you can also use braces, too {}. But...

int* a = new int[size]; // this array is probably full of junk

(Some debug allocators put a special fill pattern in newed memory, for debugging purposes, but that's nothing to do with C++. e.g. the Visual C++ C runtime's debug allocator set each byte of newly allocated memory to the value 0xCDCDCDCD)

- finally, I'm not up to speed with C++11, but believe you can write

int a[N]{}; // C++11 code

as well as

int a[N] = {}; // C++ code

Andy

PS If someone has spotted a really clear explanation of initialization in C++, please post a link. Thanks!
Last edited on
Topic archived. No new replies allowed.