c++ arrays memo

November 30th, 2010 by xrigher Leave a reply »

1. arrays initialization

under GCC, when you create an array statically, it’s not initialized. while you create it dynamically, it’s initialized.
here is the test code:

int main () {

	int N(1000000);

	// statically created array, not initialized
	int a[N];
	for(int i = 0; i < N; ++i) {
		if(a[i] != 0) {
			cout << "a[N] is not all zero!!!" << endl;
			break;
		}
	}

	// dynamically created array, initialized
	int *b;
	b = new int[N];
	for(int i = 0; i < N; ++i) {
		if(b[i] != 0) {
			cout << "b[N] is not all zero!!!" << endl;
			break;
		}
	}
	// dynamically created array, initialized	
	int *c;
	c = new int[N]();
	for(int i = 0; i < N; ++i) {
		if(c[i] != 0) {
			cout << "c[N] is not all zero!!!" << endl;
			break;
		}
	}
}

2. return array from function

Arrays of other types are typically returned via reference:

void retArray( (int*)& p, unsigned& size )
{
	size = 4;
	p = new int[ size ];
	for (int n = 1; n < 4; n++)
		p[ n ] = n;
}
Advertisement

Leave a Reply