gpt4 book ai didi

c++ - ProjectName.exe已触发断点

转载 作者:行者123 更新时间:2023-12-02 10:57:26 24 4
gpt4 key购买 nike

在运行程序时,它可以正常运行,但始终会引发此错误。它说错误来自行:

int* temp = new int[length];

我不知道为什么会这样。程序按升序返回数组,但随后抛出断点。
void mergeSort(int *a, int low, int high)
{
if (low == high)
return;
int q = (low + high) / 2;
mergeSort(a, low, q);
mergeSort(a, q + 1, high);
merge(a, low, q, high);
}

void merge(int *a, int low, int q, int high)
{
const int length = high - low + 1;
int* temp = new int[length];
int i = low;
int k = low;
int j = q + 1;

while (i <= q && j <= high)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= q)
temp[k++] = a[i++];
while (j <= high)
temp[k++] = a[j++];
for (i = low; i <= high; i++)
a[i] = temp[i];
}

最佳答案

我认为这是对temp的内存访问冲突

    int k = low;

void merge中, k变量是 temp数组索引。如果 mergeSort(a, q + 1, high)调用比 merge low参数为 q + 1,且 k超出范围0〜长度。

如果 k超出范围0〜长度。 temp[k]发生访问冲突。
我还建议在 delete[] temp函数中添加 merge
这是我的代码
int _a[] = { 5, 1, 3, 4, 2 }; // Test array!

void merge(int *a, int low, int q, int high)
{
const int length = high - low + 1;
int* temp = new int[length];
int i = low;
int k = 0; // I fixed it(low -> 0)
int j = q + 1;

while (i <= q && j <= high)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= q)
temp[k++] = a[i++];
while (j <= high)
temp[k++] = a[j++];
for (i = low; i <= high; i++)
a[i] = temp[i];

delete[] temp; // Add Delete
}

int main()
{
mergeSort(_a, 0, 5);
return 0;
}

关于c++ - ProjectName.exe已触发断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com