Whats the difference? Pointer to an array vs regular array

后端 未结 9 1748
梦如初夏
梦如初夏 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条回答
  •  Happy的楠姐
    2021-01-04 22:09

    int array[10]; declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using delete [] on that kind of array, in fact, you might crash the program if you delete it.

    When you use operator new, you allocate memory dynamically which could be slower and the memory usually comes from the heap rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and delete[] your stuff when you don't need it anymore.

    As to your array being filled with zeros, what your class material does not say is that you have to do this:

    int *arr = new int[20]; // old array
    //do magic here and decide that we need a bigger array
    int *bigger = new int[50]; // allocate a bigger array
    for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
    delete[] arr;
    arr = bigger;
    

    That code extends the array arr by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).

提交回复
热议问题