Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array name a constant pointer in C++?

Tags:

c++

I have a question about the array name a

int a[10]

How is the array name defined in C++? A constant pointer? It is defined like this or just we can look it like this? What operations can be applied on the name?

like image 813
skydoor Avatar asked Feb 28 '10 15:02

skydoor


People also ask

Are arrays constant pointers in C?

Array in C is not a constant pointer. It is a type data structure which helps store multiple elements of same type at contiguous locations. But name of array is equivalent to base address of array that is address of first element in array.

What is the relationship between array name and a pointer in C?

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 constant pointer in C?

A constant pointer is one that cannot change the address it contains. In other words, we can say that once a constant pointer points to a variable, it cannot point to any other variable. Note: However, these pointers can change the value of the variable they point to but cannot change the address they are holding.

Is an array name a variable?

Array variables are simply names you use to refer to stored data in your apps. You can name your variables whatever you want so long as the name is not already used by the system.


1 Answers

The C++ standard defines what an array is and its behaviour. Take a look in the index. It's not a pointer, const or otherwise, and it's not anything else, it's an array.

To see a difference:

int a[10];
int *const b = a;

std::cout << sizeof(a); // prints "40" on my machine.
std::cout << sizeof(b); // prints "4" on my machine.

Clearly a and b are not the same type, since they have different sizes.

In most contexts, an array name "decays" to a pointer to its own first element. You can think of this as an automatic conversion. The result is an rvalue, meaning that it's "just" a pointer value, and can't be assigned to, similar to when a function name decays to a function pointer. Doesn't mean it's "const" as such, but it's not assignable.

So an array "is" a pointer much like a function "is" a function pointer, or a long "is" an int. That is to say, it isn't really, but you can use it as one in most contexts thanks to the conversion.

like image 59
Steve Jessop Avatar answered Oct 05 '22 04:10

Steve Jessop