Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is array to pointer decay?

What is array to pointer decay? Is there any relation to array pointers?

like image 977
Vamsi Avatar asked Sep 22 '09 17:09

Vamsi


People also ask

Does STD array decay to pointer?

You probably heard that "arrays are pointers", but, this is not exactly true (the sizeof inside main prints the correct size). However, when passed, the array decays to pointer. That is, regardless of what the syntax shows, you actually pass a pointer, and the function actually receives a pointer.

What is relationship between array and pointer?

An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.

What is decay in programming?

In software development, “code decay” refers to the increasing difficulty and intricacy of code modification.

What is array of pointer explain in detail with example?

In computer programming, an array of pointers is an indexed set of variables, where the variables are pointers (referencing a location in memory). Pointers are an important tool in computer science for creating, using, and destroying all types of data structures.


1 Answers

It's said that arrays "decay" into pointers. A C++ array declared as int numbers [5] cannot be re-pointed, i.e. you can't say numbers = 0x5a5aff23. More importantly the term decay signifies loss of type and dimension; numbers decay into int* by losing the dimension information (count 5) and the type is not int [5] any more. Look here for cases where the decay doesn't happen.

If you're passing an array by value, what you're really doing is copying a pointer - a pointer to the array's first element is copied to the parameter (whose type should also be a pointer the array element's type). This works due to array's decaying nature; once decayed, sizeof no longer gives the complete array's size, because it essentially becomes a pointer. This is why it's preferred (among other reasons) to pass by reference or pointer.

Three ways to pass in an array1:

void by_value(const T* array)   // const T array[] means the same void by_pointer(const T (*array)[U]) void by_reference(const T (&array)[U]) 

The last two will give proper sizeof info, while the first one won't since the array argument has decayed to be assigned to the parameter.

1 The constant U should be known at compile-time.

like image 183
phoebus Avatar answered Sep 17 '22 13:09

phoebus