【发布时间】:2017-09-16 02:09:23
【问题描述】:
我正在尝试创建一个程序,该程序允许动态分配的数组存储一些整数,如果需要增加最大大小,然后按该顺序显示未排序和排序的数组。
我的完整代码的链接在底部。
我遇到的第一个问题是第一次需要增加大小后动态分配的数组变得混乱。相关代码如下。
while (counter <= arraySize)
{
cout <<"Please enter an integer number. Use 999999 (six 9's) to stop\n";
if (counter == arraySize) //If the counter is equal to the size of the array
{ //the array must be resized
arraySize +=2;
int *temp = new int[arraySize];
for (counter = 0; counter < arraySize; counter++)
{
temp[counter] = arrayPtr[counter];
}
delete [] arrayPtr;
arrayPtr = temp;
counter ++; //the counter has to be reset to it's original position
} //which should be +1 of the end of the old array
cin >> arrayPtr[counter];
if (arrayPtr[counter] == sentinel)
{
cout << "Sentinel Value given, data entry ending.\n";
break;
}
counter ++;
}
这会产生意想不到的操作,而不是等待标记值,它只是开始列出内存中超过该点的整数(因为没有边界检查)。
下一个问题是我的排序功能拒绝运行。我尝试在 5 个值上对此进行测试,但程序在到达代码的特定部分时就崩溃了。
函数调用使用
sorting (arrayPtr);
但函数本身看起来像这样:
void sorting (int *arr)
{
int count = 0, countTwo = 0, tempVal;
for (count = 0; arr[count] != 999999; count++) //I figured arr[count] != 999999 is easier and looks better
{ //A bunch of if statements
for (countTwo = 0; arr[countTwo] != 99999; countTwo++)
{
if (arr[countTwo] > arr[countTwo+1])
{
tempVal = arr[countTwo];
arr[countTwo] = arr[countTwo+1];
arr[countTwo+1] = tempVal;
}
}
}
}
感谢您对此问题的任何帮助。
链接到我的源代码:
http://www.mediafire.com/file/w08su2hap57fkwo/Lab1_2336.cpp
根据社区反馈,此链接将尽可能长时间保持有效。
下面的链接是我更正后的源代码。注释是为了更好地突出我犯的错误以及修复错误的答案。
http://www.mediafire.com/file/1z7hd4w8smnwn29/Lab1_2336_corrected.cpp
【问题讨论】:
-
除非出于教育原因,否则您绝不应使用原始的
new和delete。std::vector是动态数组的更好选择。 -
这是出于教育原因。
-
这将一直有效,直到我的问题得到回答。 -- 然后这个关于 SO 的问题变得毫无价值,因为该链接将不再存在。
-
我确实尝试包含相关代码来回答我的问题,这是要问的重点。如果我没有提供足够的代码,则可以提供上下文。没有人阻止您下载代码并提供有用的答案以及这样做所需的额外(如果有)上下文。但我怀疑有人提出这个问题是为了看别人争论这个问题。如果您的评论与手头的问题无关,请不要发表。
-
在给定
arraySize +=2;、for (counter = 0; counter < arraySize; counter++)和temp[counter] = arrayPtr[counter];的情况下,您在arrayPtr指向的存储空间之外读取了什么?最好我会这样做,因为您似乎对帮助 Stack Overflow 实现其为未来程序员留下解决方案存储库的目标不感兴趣。
标签: c++ arrays memory-leaks dynamic-arrays