Monday, April 21, 2008

c/c++: arrays and pointers

Sometime programmers don't make a difference between pointers to memory and arrays. They pass easily array to function that wants pointer. It's dangerous if it changes the pointer target(reallocates memory for example):

void function(int *a)
{
        delete [] a;
        a = new int[3000];
}
This will cause Segmentation fault if you pass an array to the function. The reason is that you can't do some pointer routines with arrays. The other difference in the type of &array. For int array[1];: array, &array and &(array[0]) are the same. Almost. An array is just a sequence of variables. But there is a rule, that c++ looks arrays as if they were pointers. It means that if you write array, compiler takes it as &array[0]. The value of &array and array is the same (address of the first element). But their type is different. Here &array has type "pointer to the array of T". If you add one to &array, it will point to the address of the place right after the last element of the array(just like you skipped the array).

No comments: