声明C++数组(带或不带 "new" 关键字)

Declaring C++ array with or without the "new" keyword

本文关键字:new 关键字 C++ 数组 声明      更新时间:2023-10-16

在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
}

但我建议使用字符串。它更安全,因为您不必知道已用内存的大小,字符串的内存是自动分配的。