带有指向字符数组C ++的指针的问题 [英] Issue with pointer to character array C++
问题描述
我有什么我认为应该是一个非常简单的代码片段写,虽然我无法编译的原因,我不明白。
以下简化代码不会编译:
char buffer [9] =12345678
char * pBuffer =& buffer;
编译器(g ++)会引发以下错误:
错误:无法在初始化中将'char(*)[9]'转换为'char *'
C ++不是我的本地语言,但我所看到的地方告诉我这应该工作。非常感谢任何想法或建议。
而不是取数组的地址,写
char buffer [9] =12345678;
char * pBuffer = buffer;
编辑:这是否意味着?
-
长度为
T
的数组n
是n
T
-
指针是内存地址。
因此,的操作数(在 sizeof(buffer)
, buffer
不会衰减为指针)
2。
该表达式用作一元& (在& buffer
, buffer
不会衰减为指针)
或
3。
表达式是字符串文字初始值一个字符数组( char someBuffer [3] =ab
,字符串文字ab
,不衰减到指针)。
这在标准的6.2.2.1节:
729除非是操作数of the sizeof运算符或一元&运算符,或是用于初始化数组的字符串文字,具有类型数组类型的表达式将转换为指向数组对象的初始元素并且不是左值的类型指向类型的表达式。
因此,所有你需要做的创建一个指针 char * pBuffer
到数组中的第一个字符是
char * pBuffer = buffer;
I have what I thought should be a very simple snippet of code to write, though I'm unable to compile for a reason which I do not understand.
The following simplified code will not compile:
char buffer[9] = "12345678";
char* pBuffer = &buffer;
Compiler (g++) throws the following error:
error: cannot convert 'char (*)[9]' to 'char*' in initialization
C++ isn't exactly my "native" language, but everywhere I've looked tells me this should work. Any ideas or advice is greatly appreciated.
Instead of taking the address of the array, write
char buffer[9] = "12345678";
char *pBuffer = buffer;
Edit: What does it all mean?
An array of type
T
of lengthn
is a (contiguous) sequence ofn
T
's in memory.A pointer is a memory address.
So for example, the following code
char a[5] = "hello";
char *p = "world";
corresponds to the following situation in memory:
In your code, you have created an array
char buffer[9] = "12345678";
in just the same way as the array char a[5] = "hello"
was created. You intend to create a pointer char *
which points to the first character of the array, just as char *p
above points to the first character of the array "world"
.
When an expression of type "array of type" (here buffer
) is used, it always "decays" to a pointer to the first element unless
1.
the expression is used as the operand of sizeof (in sizeof(buffer)
, buffer
does not decay to a pointer)
2.
the expression is used as the operand of unary & (in &buffer
, buffer
does not decay to a pointer)
or
3.
the expression is a string literal initializer for a character array (in char someBuffer[3] = "ab"
, the string literal "ab"
, an array, does not decay to a pointer).
This is laid out in section 6.2.2.1 of the standard:
729 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.
As a result, all that you need to do to create a pointer char *pBuffer
to the first character in your array is write
char *pBuffer = buffer;
这篇关于带有指向字符数组C ++的指针的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!