我有这个代码。
int x[5];
printf("%d\n",sizeof(x) );
int *a;
a = new int[3];
printf("%d\n",sizeof(*a));
当我将“静态”数组传递给 sizeof() 时,它返回声明数组的维数乘以该数据类型在内存中使用的字节数。但是,动态数组似乎有所不同。我的问题是我应该怎么做才能获得“动态”数组的大小?
PD:会不会跟下面的有关?
int *a;
a=new int[3];
a[0]=3;
a[1]=4;
a[2]=5;
a[3]=6;
如果我应该在“a=new int[3]”中放置一个“限制”,为什么我可以修改第三个位置。
When I pass a 'static' array to sizeof(), it returns the dimension of the declared array multiplied by the number of bytes that the datatype uses in memory.
正确,这就是整个数组大小的计算方式。
However, a dynamic array seems to be different.
这是因为您没有传递动态数组;你正在传递一个指针。指针是一种数据类型,其大小与它可能指向的内存块的大小无关,因此你总是得到一个常量值。当您为动态大小的内存块分配内存时,您需要存储分配的大小以供将来引用:
size_t count = 123; // <<== You can compute this count dynamically
int *array = new int[count];
cout << "Array size: " << (sizeof(*array) * count) << endl;
C++14 将拥有变长数组。当您检查 sizeof
时,这些数组将提供合适的大小。
Could it be related to the following? [...]
不,这是无关的。您的代码片段显示未定义的行为(写入已分配内存块的末尾),这意味着您的代码无效。它可能会立即崩溃、稍后导致崩溃或表现出其他任意行为。