简体   繁体   English

C ++:char * vs char(*)[]

[英]C++: char* vs char(*)[]

I'm new with C++ and came to this problem, here is my code: 我是C ++的新手,遇到了这个问题,这是我的代码:

shared_ptr<char[]>var(new char[20]);

char *varptr = *(var.get());

So I'm creating smart pointer of char array. 因此,我正在创建char数组的智能指针。

The problem that I'm having is that during compilation it gives me error saying: 我遇到的问题是在编译期间它给我错误提示:

cannot convert argument 1 from 'char *' to 'char(*)[]'

As the declaration of shared_ptr::get says T* get() const noexcept; 就像shared_ptr::get的声明中所说的T* get() const noexcept; it returns the pointer of template, in my case pointer to char[] . 它返回模板的指针,在我的例子中是char[]指针。 Dereferencing it should give me the char[] and assigning it to char* should be ok. 取消引用它应该给我char[]并将其分配给char*应该可以。

It seems like I'm missing something and can't figure out what. 似乎我缺少了某些东西,无法弄清楚是什么。

What is the difference between char* and char(*)[] ? char*char(*)[]什么区别? Isn't char(*)[] just a pointer of char array? char(*)[]只是char数组的指针吗? Shouldn't assigning it to char* be ok? 不应该将其分配给char*吗?

char(*)[] is a pointer to an array (of unknown size) of char , it can point to an array. char(*)[]是指向的(未知大小的)的阵列char ,它可以指向的数组。

char* is a pointer to a char , it can point to an element of an array. char*是一个指向char ,它可以指向数组的一个元素。

Semantically the two types are very different things. 语义上这两种类型是完全不同的东西。

To get a char * from a char(*)[] , you need to get a pointer to an specific element of the array (typically the first element): 要从char(*)[]获得char * ,您需要获得一个指向数组特定元素(通常是第一个元素)的指针:

char* varptr = &(*var.get())[0];

And if all you want is a string, then use std::string instead. 如果只需要一个字符串,则使用std::string代替。


To explain the difference between pointer to element, and pointer to array, consider the following array: 为了解释指向元素的指针和指向数组的指针之间的区别,请考虑以下数组:

char a[3];

A pointer to the first element ( a[0] ) can be expressed as &a[0] , which is what plain a decays to. 的指针的第一个元素( a[0]可以表示为&a[0]这是普通的a衰变到。 A pointer to the whole array is &a . 指向整个数组的指针是&a

If we show it how it's laid out in memory, with some "pointers" added, it's like this: 如果我们显示它在内存中的布局方式,并添加一些“指针”,则如下所示:

+------+------+------+-----
| a[0] | a[1] | a[2] | ...
+------+------+------+-----
^      ^      ^      ^
|      |      |      |
a      a+1    a+2    |
|                    |
&a                   (&a)+1

Even through the pointers a (which is equal to &a[0] ) and &a point to the same location, they are two different pointers and doing pointer arithmetic on them will do different things. 即使通过指针a (等于&a[0] )和&a指向相同的位置,它们也是两个不同的指针,对它们执行指针算术将做不同的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM