Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.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++ 指针到指针的内存分配,为什么这是错误的?_C++_Pointers_Memory Management - Fatal编程技术网

C++ 指针到指针的内存分配,为什么这是错误的?

C++ 指针到指针的内存分配,为什么这是错误的?,c++,pointers,memory-management,C++,Pointers,Memory Management,我只是想了解各种指针概念,我有以下代码: char** a = new char*; // assign first pointer to point to a char pointer char b[10] = "bla bla"; *a = new char; //assign second pointer a block of memory. -> This looks wrong to me!! (**a) = b[2]; 那么,第二个“指针”内

我只是想了解各种指针概念,我有以下代码:

char** a = new char*; // assign first pointer to point to a char pointer

    char b[10] = "bla bla";
    *a = new char; //assign second pointer a block of memory.  -> This looks wrong to me!!  
    (**a) = b[2]; 
那么,第二个“指针”内存分配有什么问题呢?它跑来跑去,但是感觉不对

编辑:


谢谢你澄清这一点!我学到了一些东西

> P> >没有什么错,除了使用动态内存分配,在C++中有很多坏的风格。

< P>没有错误,除了使用动态内存分配在C++中是相当糟糕的风格。

<代码> *a=新char;
表示使用默认构造函数创建单个char变量。

它相当于
*a=newchar()
并将刚刚创建的变量的地址分配给指针a

*a=新字符
表示使用默认构造函数创建单个char变量。
char** a = new char*;  // a is a pointer to a pointer to a type char. allocate a new pointer variable and make a point to it.
char b[10] = "bla bla"; // define a char array.
*a = new char; // allocate a new char and make the pointer whose address is in a point to it.
(**a) = b[2]; // copy the 3rd char of b to the char whose address is pointed by a.
它相当于
*a=newchar()并将刚创建的变量的地址分配给指针a

它“错误”的唯一原因是不清楚。你显然同意这是不清楚的

char** a = new char*;  // a is a pointer to a pointer to a type char. allocate a new pointer variable and make a point to it.
char b[10] = "bla bla"; // define a char array.
*a = new char; // allocate a new char and make the pointer whose address is in a point to it.
(**a) = b[2]; // copy the 3rd char of b to the char whose address is pointed by a.
在某些情况下,如果有更好的名称和更好的类结构,那么类似的代码可能是“正确的”,因为目标是明确的,也消除了对方法的怀疑。

它“错误”的唯一原因是不清楚。你显然同意这是不清楚的


在某些情况下,如果有更好的名称和更好的类结构,那么类似的代码可能是“正确的”,因为目标是明确的,消除了对方法的怀疑。

从技术上讲,它没有什么问题


但是,在同一代码页上显式分配指向单个元素的指针是不常见的。在实践中,你不会经常这样做,因为你很少会说“如果你需要了解FooBar,问问Tom,Tom就是我。”

这在技术上没有什么问题


但是,在同一代码页上显式分配指向单个元素的指针是不常见的。在实践中,你不会经常这样做,因为你很少会说“如果你需要了解FooBar,问问Tom,Tom就是我。”

从技术上讲,没什么错。但这种风格似乎很少使用。

从技术上讲,没有什么错。但这种风格似乎很少使用。

嗯。。。。没什么问题。你为什么认为有什么问题?如果您试图将
*a
视为C字符串,那么您就不能这样做,但在其他方面,您的代码是正常的。这在技术上是正确的。但你到底想达到什么目的呢。。。。没什么问题。你为什么认为有什么问题?如果您试图将
*a
视为C字符串,那么您就不能这样做,但在其他方面,您的代码是正常的。这在技术上是正确的。但是你到底想达到什么目的呢。。。或者,如果出于某种模糊的原因需要双指针,char a='a';char*ap=&a;字符**应用程序=&ap;字符a='a'。。。或者,如果出于某种模糊的原因需要双指针,char a='a';char*ap=&a;字符**应用程序=&ap;