开发者

Array as array[n] and as pointer array*

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;
开发者_JAVA百科    int* d = new int[5];
    std::cout << *c << std::endl; //prints 2 - ok
    c = d; //works ok!

    return 0;
}


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜