英文:
C++ Code with Global Dynamic Array Stops in the Sort Function
问题
我一直在尝试编写一个用户定义的数组,然后最终对其进行排序,但当代码达到排序函数时,代码最终停止。 代码如下:
#include <iostream>
using namespace std;
int array_size;
int* array = new int[array_size];
void create_array_cmd()
{
cout << "请键入所需的数组大小:";
cin >> array_size;
cout << "请输入您希望保存的数字字符:" << endl;
for (int i = 0; i < array_size; i++)
{
cout << "数组 [" << i + 1 << "]: ";
cin >> ::array[i];
}
}
void print_values_cmd()
{
cout << "这是您输入的值:" << endl;
for (int i = 0; i < array_size; i++)
{
cout << ::array[i] << " ";
}
cout << endl;
}
void array_sort_cmd()
{
cout << "排序后的值为:" << endl;
for (int i = 1; i < array_size; i++)
{
for (int j = i + 1; j < array_size; j++)
{
int k = ::array[i];
j = i - 1;
while (j >= 0 && ::array[j] > k)
{
::array[j + 1] = ::array[j];
j = j - 1;
}
::array[j+1] = k;
}
}
for (int i = 0; i < array_size; i++)
{
cout << ::array[i] << " ";
}
}
int main()
{
create_array_cmd();
print_values_cmd();
array_sort_cmd();
}
此外,当我在主函数的最后添加以下内容:
delete array[];
代码将不再工作。不知何故,代码将正常工作,直到您输入多于2个值。
英文:
I've been trying to code a user-defined array then eventually sort it out but the code eventually stops when it reaches the sort function. The code is as follows:
#include <iostream>
using namespace std;
int array_size;
int* array = new int[array_size];
void create_array_cmd()
{
cout << "Please input your desired array size: ";
cin >> array_size;
cout << "Please key-in the numeric characters you wish to save: " << endl;
for (int i = 0; i < array_size; i++)
{
cout << "Array [" << i + 1 << "]: ";
cin >> ::array[i];
}
}
void print_values_cmd()
{
cout << "Here are the values you entered: " << endl;
for (int i = 0; i < array_size; i++)
{
cout << ::array[i] << " ";
}
cout << endl;
}
void array_sort_cmd()
{
cout << "The sorted values are: " << endl;
for (int i = 1; i < array_size; i++)
{
for (int j = i + 1; j < array_size; j++)
{
int k = ::array[i];
j = i - 1;
while (j >= 0 && ::array[j] > k)
{
::array[j + 1] = ::array[j];
j = j - 1;
}
::array[j+1] = k;
}
}
for (int i = 0; i < array_size; i++)
{
cout << ::array[i] << " ";
}
}
int main()
{
create_array_cmd();
print_values_cmd();
array_sort_cmd();
}
Also, when I add
delete array[];
at the very end of the main function, the code won't work anymore. Somehow, the code will work fine until you input more than 2 values.
答案1
得分: 1
array
和 array_size
被声明为全局变量,并在开头进行初始化。因此,在尝试为 array
分配内存时,array_size
的值将为 0
。
您可以在请求用户输入后分配内存,或者更好地使用 std::vector<int>
。
英文:
array
and array_size
are declared as global variables and initialized at the beginning. So array_size
will have value 0
when you are trying to allocate memory for array
.
You can allocate memory after asking for user input or better still to use std::vector<int>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论