声明C++数组(带或不带 "new" 关键字)
Declaring C++ array with or without the "new" keyword
在C++中,这有什么区别:
char example[10];
而这个:
char* example = new char[10];
在这两种情况下,我都没有初始化数组的内容,而只是想在内存中获取分配给字符数组的 10 个字节。在这两种情况下,我打算使用 sprintf(( 为它们分配一个字符串值,没有中间步骤。
这个:
char example[10];
将example
声明为包含 10 个元素的char
数组。 如果在文件范围内声明,则此数组通常驻留在数据段中,而如果在块范围内声明,则通常驻留在堆栈上。
相比之下,这:
char* example = new char[10];
声明example
为指向char
的指针,并用指向动态分配内存的指针对其进行初始化,该指针指向 10 个成员的char
数组的第一个成员。 此动态分配的内存通常驻留在堆上。
另请注意,new
特定于C++。
char example[10];
example
是一个包含 10 个字符的数组。 根据上下文,它具有自动或静态存储。大小只能是编译时常量。数组将自动销毁和解除分配。
char* example = new char[10];
example
是一个指针。它不是一个数组。它指向动态存储中数组的第一个元素。动态数组的大小可以在运行时确定。数组不会自动销毁和解除分配。如果未解除分配,内存将泄漏。
动态分配通常比静态或自动分配慢。另一方面,可用于自动存储的内存量通常非常有限。
应避免使用裸露的指针。最佳做法是在需要动态数组时使用智能指针或 RAII 容器,例如std::vector
。
主要区别在于,在您的第一个示例中,您必须已经知道 at 声明这个 char 数组的大小,但在第二个示例中,您是用指针声明 char 数组,指针指向某个值。这意味着您只能在不知道 char 数组大小的情况下声明一些 char 指针。它对于程序非常有用,其中用户必须写他的昵称作为输入,昵称的最大长度可以是 10 个字符,但可以少于 10 个字符,这意味着您必须使用指针进行动态分配内存,以免使用太多未使用的内存。
例如:
int main()
{
char nm[10]; //Create char array, where you will save an input
char* nickname; //Declare pointer
std::cout << "Nickname: " << std::endl;
fflush(stdin);
gets(nm); //Save input
// Here we go find the size of used memory in char array nm
int size_of_nm = 0;
for (char i : nnnn)
{
if (i == ' ') //If char i is equal to zero character, we find the size of used
{ //memory in char array nm
break;
}
else //If i is not equal to zero character, we do not find the size of used
{ //memory in char array nm and loop will continue
size_of_nm++; //Size counter plus one
}
}
nickname = new char[size_of_nm + 1]; //Create new pointer on char array and set the
//size of used memory in char array
//plus one, because the char array is always
//ending with zero character
}
但我建议使用字符串。它更安全,因为您不必知道已用内存的大小,字符串的内存是自动分配的。
- 声明C++数组(带或不带 "new" 关键字)
- 在 Objective-C++ -> EXC_BAD_ACCESS Error 中使用"new"关键字
- 如何在堆上初始化线程?(使用 "new" 关键字)
- 如何在不使用 "new" 关键字的情况下解除分配创建的对象的内存?
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 野牛解析器无法识别"New"关键字
- 'new'关键字如何工作?我最近才知道新关键字
- 为什么当我使用"new"关键字声明数组指针时无法删除它
- 如果我不使用 new 关键字,可能会出现内存泄漏吗?
- 'new'关键字和类存储
- 说明何时在C++中使用 "new" 关键字
- 在没有“new”关键字的情况下实例化类会导致在堆栈或堆上创建其内部变量
- C++对象初始化,无需 new 关键字并使用指针
- 当对象不使用 new 关键字但父对象在堆中时,对象是否存储在堆栈或堆中
- 在没有 new 关键字的情况下初始化C++对象的内存从何而来
- 模板类的构造函数在使用 new 关键字时调用类型构造函数
- 循环中的多个对象C++而不"new"关键字
- C++:结构和new关键字
- 删除c++中的对象,以及new关键字
- New关键字用作标识符