If you
want to be able to alter the size of
your array at run time,then declare
dynamic arrays. These are done with
pointers and the new operator. For the
basics on pointers,read the pointers
section.Allocate memory using new,and then
you access the array in the same way
you would a static array. For example,int* arrayPtr = new int[10]; for
(int i = 0; i < 10; i++) {
arrayPtr[i] = i; }The memory picture is identical to the
static array,but you can change the
size if you need to. Don’t forget you
must deallocate the memory before
allocating new memory (or you will
have a memory leak).delete [] arrayPtr; // the []
is needed when deleting array pointers
arrayPtr = new int[50]; . . .When you’re completely done with the
array,you must delete its memory:delete [] arrayPtr;
Dynamic multi-dimensional arrays are
done in a similar manner to Java. You
will have pointers to pointers. For an
example,see a
我的理解是,C中的数组只是引用数组中第一个元素的内存地址.
那么int * pointerArray = new int [10]有什么区别?和int数组[10];如果有的话
我做了一些测试,似乎表明他们做同样的事情.网站错了还是我读错了?
#include <cstdlib> #include <iostream> using namespace std; int main(int argc,char** argv) { // Initialize the pointer array int *pointerArray = new int[10]; for (int i = 0; i < 10; i++){ pointerArray[i] = i; } // Initialize the regular array int array[10]; for (int i = 0; i < 10; i++){ array[i]= i; } cout << *(pointerArray + 5) << endl; cout << *(array + 5) << endl; cout << pointerArray[5] << endl; cout << array[5] << endl; cout << pointerArray << endl; cout << array << endl; return 0; }
输出:
5 5 5 5 0x8f94030 0xbfa6a37c
我试图按照网站上的描述“动态地重新调整”我的指针数组,但是我的新(较大)指针数组最后填满了0,这不是很有用.
解决方法
当您使用operator new时,您可以动态分配内存,这可能较慢,内存通常来自堆,而不是程序的堆栈(尽管并非总是).这在大多数情况下更好,因为堆栈空间比堆空间更受限制.但是,当您不再需要它时,您必须注意内存泄漏并删除[]您的东西.
至于你的数组充满了零,你的课堂材料没有说,你必须这样做:
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;
该代码将阵列arr再增加30个元素.请注意,您必须将旧数据复制到新数组中,否则它将不会存在(在您的情况下,所有内容都将变为0).