当我运行以下代码时,它适用于C:
#include<stdio.h>
int main(void)
{
const int x=5;
char arr[x];
printf("%d",sizeof(arr));
}
Run Code Online (Sandbox Code Playgroud)
但是,不仅我之前读过const合格的变量不是real常量(这就是为什么它们不能在case条件下使用switch-case),但IBM的以下链接证实了(IBMLINK)并说:
const int k = 10;
int ary[k]; /* allowed in C++, not legal in C */
Run Code Online (Sandbox Code Playgroud)
为什么我允许const在C中使用合格变量作为数组大小而没有任何错误?
我已经开始学习 C++。我读到只能在运行之前设置数组的大小,并且可以在运行时设置动态数组。所以我期待这会失败,但它没有:
#include <iostream>
int main() {
using namespace std;
int size;
cout << "enter array size:";
cin >> size;
int i, score[size], max; //array size set to variable doesn't fail
cout << endl << "enter scores:\n";
cin >> score[0];
max = score[0];
for (i = 1; i < size; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
cout << "the highest score is " << max << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是最近的 C++ 编译器中的新功能吗?它是否意识到我需要一个动态数组并创建它?
我有一个想要初始化的数组
char arr[sizeof(int)];
Run Code Online (Sandbox Code Playgroud)
该表达式的计算结果是否为编译时常量或导致函数调用?
我需要创建一个特定对象的数组,其中我需要的数字依赖于一个单独的变量,解释它的最佳方法是使用psudo代码示例:
int num = 4;
for(int i=0;i<num;i++){
object_type arrayi [dynamic size];
}
Run Code Online (Sandbox Code Playgroud)
所以我需要4个数组,每个数组都有名称array0,array1,array2和array3,它们都必须是动态数组.无论如何在C++中这样做?