gpt4 book ai didi

c++ - 为什么指向 char 的指针与指向 char 作为数组元素的指针的行为不同?

转载 作者:行者123 更新时间:2023-11-30 01:06:15 26 4
gpt4 key购买 nike

我很好奇为什么这两段代码给出不同的输出

#include <iostream>
using namespace std;
int main(){
char *arr=new char;
arr="monday";
cout<<arr<<endl;//gives the output "monday"

char *newArr=new char[3];//i want array of three pointers not the size of a string to be 2+1
newArr[0]="monday";//err
cout<<newArr[0]<<endl;


system("pause");
return 0;

}

我的意思是他们不是都指向第一个字母的地址吗

问题是“arr”和“newArr[0]”有什么区别

最佳答案

你遇到的麻烦比你想象的要多......

char *arr=new char;
arr="monday";

您首先让arr 指向您分配的单个 字符。然后重新分配 arr 并使其指向其他地方(指向文字 "monday" 数组的第一个字符)。这会导致泄漏,因为您分配的原始内存已丢失且无法再访问。

至于

char *newArr=new char[3];
newArr[0]="monday";

在这里,您使 newArr 指向三个单个字符的“数组”,然后尝试使单个字符 newArr[0] 指向字符串文字。


有点不同,你尝试用什么做

char* arr = new char;

基本上等同于

char arr[1];

char* newArr = new char[3];

相当于

char newArr[3];

解决问题的标准方法当然是使用 C++ 标准 std::string类(class)。比如

std::string arr;
arr = "monday";

并与 std::vector 一起或 std::array第二个:

std::array<std::string, 3> newArr;
newArr[0] = "monday";

最后,关于arrnewArr[0]的区别。一个是指向 char 的指针,类型为 char*。另一个是 char(但是 newArr 是指向 char 的指针,就像 arr 一样)。

关于c++ - 为什么指向 char 的指针与指向 char 作为数组元素的指针的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46642344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com