【发布时间】:2014-10-27 19:01:59
【问题描述】:
我一直在尝试用 C++ 实现一个动态数组,但在指针引用方面遇到了一些麻烦。
使用以下代码,我遇到了分段错误。
如果我使用数组和大小作为全局变量,应用程序就可以工作。我知道我可以做到,但我想知道为什么它不起作用。 我想我丢失了指针数组指针引用,但我不知道如何在方法中维护它。
我不想使用像 vector 这样的 STL 容器。
感谢您的帮助。
void addElement(int newElement, unsigned int * array, int& size ){
/* create a temp array in order to copy the contents from the current array
* it is needed because we want to increase the size of the array */
unsigned int* temp = new unsigned int[size + 1];
// copy all the data from array to temp
for (int x=0; x < size; x++){
*(temp + x) = array[x];
}
// add the new element
*(temp + size) = newElement;
size++;
// release the memory from the temp array
delete [] array;
// the temp array turn into the temp array, that contains all the elements
array = temp;
}
int main(){
unsigned int * array;
int size;
addElement(1, array, size);
addElement(2, array, size);
addElement(3, array, size);
cout << array[1];
return 1;
}
【问题讨论】:
-
[OT]:
*(temp + x)和array[x]表示法之间可能是一致的。 -
“我不想使用像 vector 这样的 STL 容器。” 所以基本上你是在说“我不想使用提供给我的经过验证的高效实现,但宁愿利用我的时间来实现一些可能效果不佳或速度不快的东西。”标准库的存在是有原因的。 使用它。
-
嗨 cdhowie,我没有使用矢量,因为这个问题与我正在进行的练习有关,矢量是限制之一。在以后的项目中,我肯定会使用vector。谢谢!
标签: c++ arrays pointers segmentation-fault