Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我试着用typedef定义一个动态增长的数组,它最多可以工作79个索引,除此之外,它没有,有人能解决这个问题吗?_C++_Arrays_C++11_Typedef - Fatal编程技术网

C++ 我试着用typedef定义一个动态增长的数组,它最多可以工作79个索引,除此之外,它没有,有人能解决这个问题吗?

C++ 我试着用typedef定义一个动态增长的数组,它最多可以工作79个索引,除此之外,它没有,有人能解决这个问题吗?,c++,arrays,c++11,typedef,C++,Arrays,C++11,Typedef,在不给出显式大小的情况下,它可以工作到索引79。它在索引79处打印值200,但当我将索引增加1,即80时,它不打印任何内容,程序终止 #include <iostream> using namespace std; typedef int list[]; int main() { list myList{}; myList[79]={200}; cout<<myList[79]; // OUTPUT: 200 return 0; } #包括 使

在不给出显式大小的情况下,它可以工作到索引79。它在索引79处打印值200,但当我将索引增加1,即80时,它不打印任何内容,程序终止

#include <iostream>
using namespace std;

typedef int list[];
int main() {
   list myList{};
   myList[79]={200};
   cout<<myList[79]; // OUTPUT: 200
   return 0;
}
#包括
使用名称空间std;
typedef int list[];
int main(){
列出myList{};
myList[79]={200};

cout首先,尝试执行以下操作:

list myList {};
cout << sizeof(myList) << endl;
// Prints 0, since no elements 
// Note, the number does not signifies the number of elements,
// it signifies the number of bytes.
list myList{};

对于初学者来说,代码不是合法的C++。如果编译器接受它,那么编译器设置不够严格。

如果您的编译器接受它,那么它会将其视为一个零大小的数组,而不是一个“动态增长的数组”,这并不是什么问题


您正在访问超出范围的数组,因此该行为定义不足(正如它适用于无效的C++一样)。

这是一个未定义行为的示例。没有“动态增长数组”这样的东西C++中的C++不工作。结果代码会导致随机内存损坏,这就足够糟糕了,只有当你尝试使用那个特定索引时才会导致立即崩溃,但是整个事情都是未定义的行为。;
是大小为0的数组。@SamVarshavchik我使用一个从1到79的循环初始化了数组,并打印了整个数组,它确实打印了从1到79的值,但没有打印。它怎么可能随机初始化索引到79,并且总是在80时崩溃。仍然很困惑。我的意思是,数组是如何动态增长的到79,没有明确的大小…@HamzaKhan您看到的行为纯粹是偶然/巧合。请阅读。@rarwrex if myList[79]={200}不是在创建一个元素,那怎么会呢cout@HamzaKhan因为它首先是未定义的行为,特别是因为您执行命令将值分配给此内存位置。读取缓冲区溢出错误。谁知道您使用此分配在内存中覆盖了什么。如果cout@HamzaKhan未定义的行为可以产生任何影响,包括你所看到的。如果你试图在写之前读取一个值,它可能是垃圾。
list myList {};
cout << sizeof(myList) << endl;
// Prints 0, since no elements 
// Note, the number does not signifies the number of elements,
// it signifies the number of bytes.