3

What is the difference when array is declared as array[n] or as pointer array* according to example below? I guess that for example both 'a' and 'c' point at the first element of array, but they behave different.

#include <iostream>

int main() { 
    int a[3] = {1};
    int b[5];
    std::cout << *a << std::endl; //prints 1 - ok
    //a = b; //error during compilation

    int* c = new int[3];
    c[0] = 2;
    int* d = new int[5];
    std::cout << *c << std::endl; //prints 2 - ok
    c = d; //works ok!

    return 0;
}
scdmb
  • 15,091
  • 21
  • 85
  • 128
  • 1
    Please take a look at the C FAQ: http://c-faq.com/aryptr/index.html – NPE Sep 14 '11 at 14:00
  • 2
    "This was closed to soon. The linked question is very similar, but the answers are also extremely long and complex. A much shorter and to-the-point answer can be provided herein that would help the community." -- I agree with this, so have at it – Jeff Atwood Sep 15 '11 at 06:23
  • 1
    Array is **NOT** pointer. http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c – Furqan Sep 15 '11 at 15:02

2 Answers2

5

Long story short - they are essentially the same, but ever so slightly different.

From what I've gathered from http://c-faq.com/aryptr/aryptr2.html , whilst they can both act as a pointer to the front of an array, when you declare an array as

int a[3];

you are essentially binding the size of '3' to your variable a, along with the fact it's an array. Hence, when you try to assign b, of size 5 to a, you get a compilation error.

In contrast, when you write

int * a;

You are merely saying 'this is a pointer that may point to an array', with no promise on the size.

Subtle, isn't it?

Tetigi
  • 584
  • 1
  • 6
  • 20
  • 4
    Actually, the latter says `This is a pointer, which may or may not point to an array, and the developer has to keep track." – MSalters Sep 15 '11 at 15:15
0

The difference between the following two lines:

int g[10];

and

int* h = new int[10];

is that the second is dynamically-allocated, whereas the first is statically-allocated.

For most purposes, they are identical, but where in memory they end up living is different.

warren
  • 32,620
  • 21
  • 85
  • 124
  • They are not identical. The array has a size, and can be passed to `void MyFunc(int g[10])`, but a pointer cannot. – Mooing Duck Sep 15 '11 at 17:16
  • 1
    @Mooing Duck - you most certainly can pass a pointer to the function as requested (unless something has changed since gcc 3) – warren Sep 15 '11 at 17:31
  • http://ideone.com/7bmwx Better example. Type of `int g[10]` clearly shown as `int [10]` and type of `int *h` as `int*&`, and an example function where an array binds and a pointer won't – Mooing Duck Sep 15 '11 at 17:38