Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between two array declaration methods c++

These of 2 of the probably many ways of declaring arrays (and allocating memory for them) in c++

1. int a[3];

2. int *b = new int[3];

I want to understand how c++ is treating the two differently.

a. In both cases, i can access array with the following syntax: a[1] and b[1]

b. When i try cout<< a and cout<< b, both print the addresses of first element of respective arrays.

It looks to me as if both a and b are being treated as pointers to first elements of arrays.

c. But strangely, when i try to do cout << sizeof(a) and sizeof(b) they print different values - 4 and 12 respectively.

I don't understand why in case of sizeof(b), the size of entire array is being printed.

like image 740
Nitin Garg Avatar asked Jul 05 '11 21:07

Nitin Garg


2 Answers

a is an array (type int [3])
b is a pointer (type int*)

In C++ they are completely different things.

The sizeof an array is the number of elements times the size of each element.
The sizeof a pointer is independent of the size of the array (usually 4 or 8 bytes).

The only thing that arrays and pointers have in common is that arrays often "decay" to pointers in several situations. That's what's happening when you print out their value.

like image 117
Peter Alexander Avatar answered Sep 28 '22 16:09

Peter Alexander


As you noted, it seems as though both a and b are pointers to the start of the array. But in reality, only b is a pointer. a is actually an array.

The difference between the two is subtle when writing (or reading) code. The variable a is treated as a regular variable (just like an int or double) in that it has an automatically allocated portion of memory assigned to it. For comparison, suppose you had declared int i. The variable i is the name given to a certain set of contiguous bytes in memory to hold an integer value (4 bytes on your machine). Similarly, a is the name given to the set of contiguous bytes which holds your array (12 bytes in your case).

In contrast b is only a pointer to a single memory location. In your case, there is a block of 12 bytes which is dynamically allocated (via new int[3]). b itself is an automatically allocated 4-byte pointer which points to the first int value in that 12 byte block.

So they really are two different kinds of things. This is made less clear to C++ programmers. One reason for this is the fact that you can use the [] operator on both types. Another reason is that arrays implicitly degenerate to pointers in several situations (e.g. in the function void Foo(int a[3]);, a is not actually an array, but a pointer to the beginning of the array). But don't be fooled - arrays are not pointers (as many people claim), and pointers are definitely not arrays.

like image 28
Ken Wayne VanderLinde Avatar answered Sep 28 '22 15:09

Ken Wayne VanderLinde