作者:C3calm_daidai_649 | 来源:互联网 | 2023-05-26 12:38
我正在尝试学习C++,数组和指针.我决定实现插入排序算法.所以,这是我的代码和错误的输出.我该怎么做才能纠正它?你能否告诉我我的错误是什么?如果这是一个常见的错误我应该避免什么?
我的代码:
// InsertionSort.cpp
#include "stdafx.h"
#include
int DeclareAnInteger();
int* DeclareAndShowTheArray(int n);
int* InsertionSort(int *A, int n);
int main()
{
int n = DeclareAnInteger();
int *A;
A = DeclareAndShowTheArray(n);
int *B;
B = InsertionSort(A, n);
system("PAUSE");
return 0;
}
int DeclareAnInteger()
{
int n;
std::cout <<"Please enter a positive integer n: ";
std::cin >> n;
return n;
}
int* DeclareAndShowTheArray(int n)
{
int *A;
A = (int *)alloca(sizeof(int) * n);
for (int i = 0; i > A[i];
}
std::cout <<"The unsorted array is: ";
for (int i = 0; i = 0 & A[m] > key)
{
A[m + 1] = A[m];
m = m - 1;
}
A[m + 1] = key;
}
std::cout <<"The sorted array is: ";
for (int i = 0; i
我的输出:
1> Some program..:
这是一个很大的问题:
A = (int *)alloca(sizeof(int) * n);
该alloca
函数分配在堆栈上,而当函数返回给你一个迷失指针,它将会丢失不确定的行为,当你解引用这个指针.
如果您正在编程C++然后使用new
,如果您编程C然后使用malloc
.