我试图理解字符串、数组和指针之间的关系。
我正在阅读的这本书有一个程序,它在其中初始化一个变量,如下所示:
char* szString= "Name";
我理解这一点的方式是,C 风格的字符串只是一个字符数组。数组只是引用指针(存储数组的第一个值)和偏移量的简写版本。 IE。
array[5]
实际上返回从表达式 *(array+5)
求值的内容。
所以,根据我的理解和测试,szString 实际上被初始化为一个指针,该指针指向存储“名称”的数组的第一个地址。我可以推断出这一点,因为输出为:
cout << *szstring;
是字符“N”。
我对声明的理解
cout << szstring;
输出字符“Name”,就是方法cout将参数szstring解释为字符串类型,并打印出所有字符,直到NUL字符。另一方面,对于参数 *szstring
,使用了此方法的不同版本,它支持 C 风格的字符串。
因此,如果我可以初始化一个 char 类型指针来寻址 chars 数组(C 风格字符串)中的第一个元素,为什么我不能初始化一个指向整数数组中第一个元素的 int 类型指针如下:
int* intArray = {1,2,3};
最佳答案
a C-style string is simply an array of chars
正确。
An array is simply a shorthand version of referring to the pointer (which stores the first value of the array) and an offset.
不,不是。
the method cout interprets the argument szstring as a string type and prints out all the characters until the NUL character
cout
不是“方法”,而是它的operator<<
是的。
Why can a char pointer variable be initialized to a string but an int pointer variable can not be initialized to an array of integers?
简单的答案是字符串文字是特殊的,否则我们将无法使用它们。
在许多方面,包括这种方式,语言标准都规定了对字符串文字和 char*
的特殊处理。秒。
why can I not initialize an int type pointer to the first element in an array of integers
C++ 可以最终扩展了其他指针初始化的语法来做类似的事情,但它实际上并不需要,因为相反我们有更优越的:
std::vector<int> myInts{1,2,3};
关于c++ - 为什么 char 指针变量可以初始化为字符串,而 int 指针变量不能初始化为整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43564633/