Whats the difference? Pointer to an array vs regular array

后端 未结 9 1746
梦如初夏
梦如初夏 2021-01-04 21:40

I\'m familiar with Java and trying to teach myself C/C++. I\'m stealing some curriculum from a class that is hosting their materials here. I unfortunately can\'t ask the tea

9条回答
  •  轮回少年
    2021-01-04 22:19

    My understanding is that an array in C is simply a reference to the memory address of the first element in the array.

    So, what is the difference between int *pointerArray = new int[10]; and int array[10]; if any?

    What you mention is the reason for much confusion in any C/C++ beginner.

    In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the [] syntax, like in your example:

    int array[10];
    

    One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:

    int* array_pointer = array;
    

    which is the same as:

    int* array_pointer = &array[0];
    

    and this allows to access array elements in the usual way: array_pointer[3], but you cannot treat array as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).

    That said, it is also true that you can manage arrays without using the [] syntax at all and just allocate arrays by using malloc and then using them with raw pointers. This makes the "beauty" of C/C++.

    Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):

    1. the [] syntax in declarations (i.e., int array[10];) refers to both aspects at once (it gives you, as to say, a pointer and an array);

    2. when declaring a pointer variable (i.e., int* p;), you just get the pointer;

    3. when evaluating an expression (i.e., int i = p[4];, or array[4];), the [] just means dereferencing a pointer.

    Apart from this, the only difference between int *pointerArray = new int[10]; and int array[10]; is that former is allocated dynamically, the latter on the stack.

提交回复
热议问题