C++中char*与char(*)[]的区别及shared_ptr编译报错咨询
Let's walk through your problem clearly—array pointers in C++ can be tricky when you're just starting out, so it's totally normal to hit this confusion.
First, Fixing Your Code
The immediate issue is that you're overcomplicating the assignment. When you use shared_ptr<char[]>, its get() method returns a char* (a pointer to the first element of the char array), not a pointer to the entire array (char(*)[]). You don't need to dereference it at all:
shared_ptr<char[]> var(new char[20]); char *varptr = var.get(); // This works perfectly
The error you saw happened because *(var.get()) tries to dereference a char*, which gives you a single char value—not an array. Assigning a char to a char* is invalid, hence the compiler's complaint.
Explaining char* vs char(*)[]
Let's break down the two pointer types you're confused about:
1. char*
- This is a pointer to a single
charvalue. - In practice, it's commonly used to point to the first element of a char array (since array names implicitly convert to pointers to their first element).
- Example:
char arr[20] = "hello"; char* p = arr; // p points to arr[0] (the 'h')
2. char(*)[]
- This is a pointer to an array of chars (specifically, a pointer to an unknown-size char array). For a fixed-size array, it would look like
char(*)[20](pointer to a 20-element char array). - This type points to the entire array as a single object, not just its first element.
- Example:
char arr[20] = "hello"; char(*p_arr)[] = &arr; // p_arr points to the entire array
Can char(*)[] Be Assigned to char*?
Yes, but you need to dereference the array pointer first to get the array (which then "decays" to a pointer to its first element):
char arr[20] = "hello"; char(*p_arr)[] = &arr; char* p = *p_arr; // *p_arr is the array, which decays to char* pointing to arr[0]
But in your original code, this step wasn't necessary because shared_ptr<char[]>::get() already returns the char* you need directly.
Why Your Initial Assumption Was Off
You looked at the general shared_ptr::get() declaration T* get() const noexcept;, and assumed that for shared_ptr<char[]>, T is char[], so T* would be char(*)[]. However, shared_ptr has a specialization for array types (shared_ptr<T[]>) that adjusts the return type of get() to T*—which for T=char is char*, not a pointer to the array. This specialization exists to make working with array smart pointers more intuitive, matching how raw array pointers behave in most cases.
内容的提问来源于stack exchange,提问作者Ojs

