必须在编译时知道数组维度,这意味着维度必须是常量表达式
另外一点是这样的
unsigned count = 42; // not a constant expression
constexpr unsigned size = 42; // a constant expression
Run Code Online (Sandbox Code Playgroud)
我会,然后期望以下声明失败
a[count]; // Is an error according to Primer
Run Code Online (Sandbox Code Playgroud)
但事实并非如此.编译并运行良好.
还有一点奇怪的是,++count;在数组声明之后也没有引起任何问题.
用-std=c++11flag打开的程序g++4.71
这是为什么?
我有以下C++代码:
NumericVector testFromontcpp(NumericMatrix z1, NumericMatrix z2, int Nbootstrap){
int dim1 = z1.nrow();
int dim2 = z2.nrow();
int dimension = z1.ncol();
int N = dim1 + dim2;
NumericVector TKeps(Nbootstrap+1);
cout << "toto";
double bb[N][N];
cout << "toto";
return(TKeps);
}
Run Code Online (Sandbox Code Playgroud)
我用Rcpp包运行它:sourceCpp("...").如果z1.size()低于500,它的效果很好.但是对于更高的尺寸,它会在打印第二个"toto"之前崩溃并关闭R.
我想知道 :
z1.size()> 0?谢谢 !
可能重复:
C/C++:运行时的数组大小是否允许动态分配?
在下面的清单中,显然大小buf由运行时常量决定j.编译器如何生成代码以在堆栈上分配存储(不知道j编译时的值)?
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
srandom(time(NULL));
int i = random();
cout<< "random number: "<<i<<endl;
if(i%2==0)
i=2;
else
i=1;
const int j=i;
char buf[j];
std::cout<<"size of buf array: "<<sizeof(buf)<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试int根据运行时获得的大小创建并归零一个s 数组:
size = [gamePiece.availableMoves.moves count]; //debugger shows size = 1;
int array[size]; //debugger shows this as int[0] !
memset(array, 0, size);
indexes = array;
Run Code Online (Sandbox Code Playgroud)
size并且indexes都是这个类的ivars:
int size;
int* indexes;
Run Code Online (Sandbox Code Playgroud)
不过,我最终得到了一个0长度的数组.如何用指示的尺寸创建它[gamePiece.availableMoves.moves count]?
我希望用户在程序启动时定义数组的大小,我目前有:
#define SIZE 10
typedef struct node{
int data;
struct node *next;
} node;
struct ko {
struct node *first;
struct node *last;
} ;
struct ko array[SIZE];
Run Code Online (Sandbox Code Playgroud)
这有效,但是,我想删除#define SIZE,并让SIZE成为用户定义的值,所以在主函数中我有:
int SIZE;
printf("enter array size");
scanf("%d", &SIZE);
Run Code Online (Sandbox Code Playgroud)
我该如何获得该数组的值?
编辑:现在我在.h文件中有以下内容:
typedef struct node{
int data;
struct node *next;
} node;
struct ko {
struct node *first;
struct node *last;
} ;
struct ko *array;
int size;
Run Code Online (Sandbox Code Playgroud)
这在main.c文件中:
printf("size of array: ");
scanf("%d", &size);
array = malloc(sizeof(struct ko) * size); …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法来动态设置整数数组的大小取决于传递的参数.例如,这是伪代码:
int MyFunction(int number)
{
int myarr[amount of digits in number];
}
Run Code Online (Sandbox Code Playgroud)
所以当输入是13456时,那么int array[]大小应该是5.当我不知道大小的常量时,用C++做最快的方法是什么?
我正在阅读数组上的C ++ Primer plus,它显示以下内容
typeName arrayName[arraySize];
//Arraysize cannot be a variable whose value is set while the program is running"
Run Code Online (Sandbox Code Playgroud)
但是,我写了一个程序
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int array[n];
for(int i=0; i<n; i++)
{
cout<<array[i]<<endl;
}
}
Run Code Online (Sandbox Code Playgroud)
而且效果很好,我可以在运行时设置数组的大小。我没有收到任何编译错误,或者运行时崩溃。
有人可以解释发生了什么吗?
谢谢