Whats the difference? Pointer to an array vs regular array

后端 未结 9 1686
梦如初夏
梦如初夏 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:33

    Dynamically allocated:

    int * pointerArray = new int[10]; 
    

    [BTW, this is a pointer to an array of 10 ints, NOT a pointer array]

    Statically allocated (possibly on the stack):

    int array[10]; 
    

    Otherwise they are the same.

    0 讨论(0)
  • 2021-01-04 22:33

    The main difference is that some operations that are allowed on pointers are not allowed on arrays.

    0 讨论(0)
  • 2021-01-04 22:35

    The problem with understanding C/C++ arrays when coming from Java is that C/C++ distinguishes between the array variable and the memory used to store the array contents. Both concepts are important and distinct. In Java, you really just have a reference to an object that is an array.

    You also need to understand that C/C++ has two ways of allocating memory. Memory can be allocated on the help or the stack. Java doesn't have this distinction.

    In C and C++, an array variable is a pointer to the first element of the array. An array variable can exist on the heap or the stack, and so can the memory that contains its contents. And they can be difference. Your examples are int arrays, so you can consider the array variable to be an int*.

    There are two differences between int *pointerArray = new int[10]; and int array[10];:

    The first difference is that the memory that contains the contents of the first array is allocated on the heap. The second array is more tricky. If array is a local variable in a function then its contents are allocated on the stack, but if it is a member variable of a class then its contents are allocated wherever the containing object is allocated (heap or stack).

    The second difference is that, as you've realised, the first array is dynamic: its size can be determined at run-time. The second array is fixed: the compiler must be able to determine its size at compile time.

    0 讨论(0)
提交回复
热议问题