1

在 C++ 中,这之间有什么区别:

char example[10];

和这个:

char* example = new char[10];

在这两种情况下,我都没有初始化数组的内容,而只是想在内存中分配给字符数组的 10 个字节。在这两种情况下,我打算然后使用 sprintf() 为它们分配一个字符串值,而无需中间步骤。

4

3 回答 3

4

这个:

char example[10];

声明examplechar包含 10 个元素的数组。如果在文件范围内声明,则该数组通常位于数据段中,而如果在块范围内声明,则通常位于堆栈中。

相比之下,这:

char* example = new char[10];

声明example为指向 的指针char,并使用指向动态分配内存的指针对其进行初始化,该指针指向 的 10 个成员数组的第一个成员char。这种动态分配的内存通常驻留在堆上。

另请注意,这new是特定于 C++ 的。

于 2020-06-20T17:38:25.880 回答
3
char example[10];

example是一个 10 个字符的数组。根据上下文,它具有自动或静态存储。大小只能是编译时常量。数组被自动销毁和释放。

char* example = new char[10];

example是一个指针。它不是一个数组。它指向动态存储中数组的第一个元素。动态数组的大小可以在运行时确定。数组不会自动销毁和释放。如果不释放,内存将泄漏。

动态分配通常比静态或自动慢。另一方面,可用于自动存储的内存量通常非常有限。

应避免裸拥有指针。std::vector最佳实践是在需要动态数组时使用智能指针或 RAII 容器。

于 2020-06-20T17:53:12.300 回答
0

主要区别在于,在您的第一个示例中,您必须在声明此 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 == '\0') //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
}

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

于 2020-06-21T11:36:04.977 回答