C++ 编译错误:变量长度数组 (Variable Length Array) 的使用
该代码在使用变量长度数组时出现了编译错误。在 C++ 中,变量长度数组是一种非标准的语法,因此某些编译器可能无法正确处理它。
要避免该错误,可以使用常量长度数组或动态分配内存来存储数组。
使用常量长度数组:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n, int direction, int type) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (direction == 1) {
if (type == 1) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
} else {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
} else {
if (type == 1) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
} else {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
}
int main() {
const int MAX_SIZE = 100; // 定义最大数组大小
int n;
cin >> n;
if (n > MAX_SIZE) {
cout << "数组大小超出限制!" << endl;
return 1;
}
int arr[MAX_SIZE]; // 使用常量长度数组
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int type;
cin >> type;
int direction;
cin >> direction;
bubbleSort(arr, n, direction, type);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
使用动态内存分配:
#include <iostream>
#include <cstdlib>
using namespace std;
void bubbleSort(int *arr, int n, int direction, int type) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (direction == 1) {
if (type == 1) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
} else {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
} else {
if (type == 1) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
} else {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
}
int main() {
int n;
cin >> n;
int *arr = new int[n]; // 动态分配内存
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int type;
cin >> type;
int direction;
cin >> direction;
bubbleSort(arr, n, direction, type);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
delete[] arr; // 释放分配的内存
return 0;
}
选择哪种方法取决于你的具体需求。如果你事先知道数组的最大大小,使用常量长度数组可以使代码更简洁。如果数组大小未知或可能很大,则动态内存分配更灵活。但请务必在使用完动态分配的内存后及时释放它,以防止内存泄漏。
原文地址: https://www.cveoy.top/t/topic/nWrI 著作权归作者所有。请勿转载和采集!