我无法理解什么是 C 风格的字符串。新年快乐
我所知道的: 指针保存内存地址。取消引用指针将为您提供该内存位置的数据。
int x = 50;
int* ptr = &x; //pointer to an integer, holds memory address of x
cout << "&x: " << &x << endl; //these two lines give the same output as expected
cout << "ptr: " << ptr << endl;
cout << "*ptr: " << dec << (*ptr) << endl; //prints out decimal number 50
//added dec, so the program doesnt
//continue to printout hexidecimal numbers like it did for the
//the memory addresses above
cout << "&ptr: " << &ptr << endl; //shows that a pointer, like any variable,
//has its own memory address
现在我不明白的地方(使用上面的内容作为我困惑的来源): 有多种方法可以声明字符串。我正在学习 C++,但你也可以使用 C 风格的字符串(很好理解,虽然不如 C++ 字符串)
C++:
string intro = "Hello world!";
//the compiler will automatically add a null character, \0, so you don't have to
//worry about declaring an array and putting a line into it that is bigger than
//it can hold.
C 风格:
char version1[7] = {'H','i',' ','y','o','u','\0'};
char version2[] = "Hi you"; //using quotes, don't need null character? added for you?
char* version3 = "Hi you";
版本 3 是我遇到问题的地方。在这里,有一个指向 char 的指针。我知道数组名是指向数组中第一个元素的指针。
cout << " &version3: " << &version3 << endl; //prints out location of 'H'
cout << " *version3: " << *version3 << endl; //prints out 'H'
cout << " version3: " << version3 << endl; //prints out the whole string up to
//automatically inserted \0
之前,在“我所知道的”部分中,打印出指针的名称会打印出它所持有的地址。在这里,打印出指针的名称会打印出整个字符串。在“你好”周围做双引号以某种方式告诉程序:“嘿,我知道你是一个指针,你被初始化到'H'的位置,但是因为我看到这些双引号,所以在内存位置向前跳过1个字节并打印出您看到的所有内容,直到到达\0"(移动 1 个字节,因为 char 的大小为 1 个字节)。
打印出一个指针如何打印出一个字符串?在打印出一个指针名称之前,先打印出它被初始化的内存地址。
编辑:cout << &version3
打印出'H'的位置或指针的位置,version3
, 它保存着 'H' 的内存地址?
最佳答案
打印出 char*
与 cout
与打印的工作方式不同,例如 int*
与 cout
.为了与 C 风格的字符串兼容,<<
的重载版本这需要 char*
参数对待 char*
作为 C 风格的字符串。如果要打印 char*
的内存地址持有,您可以将其转换为 void*
.
是的,如果你写其中一个
char *s1 = "hi lol";
char s2[] = "hi haha";
在字符串末尾为您添加了一个 NUL ( \0
) 终止符。这两者的区别在于 s1
是一个指向字符串文字的指针,根据 C 标准,您不应该修改其内容,而 s2
是一个数组,即在堆栈上为您分配的一 block 内存,它被初始化以保存值"hi haha"
。 , 您可以随意修改其内容。为数组分配的内存量恰好足以容纳用作初始化程序的字符串,并且会自动为您确定,这就是方括号可以为空的原因。
旁注:在 C 中,如果您输入 char s[3] = "abc";
, 然后 s
将被初始化为 {'a', 'b', 'c'}
, 没有 NUL 终止符!这是因为标准中的一个条款规定,如果数组中有空间(或一些类似的措辞),此上下文中的字符串将使用 NUL 终止符初始化。在 C++ 中,情况并非如此。有关更多信息,请参阅 No compiler error when fixed size char array is initialized without enough room for null terminator .
针对您添加的问题进行编辑:如果您有 char *s = "..."
,还有你cout << &s;
, 它将打印指针 s
所在的地址被存储,而不是 s
的地址持有(s
引用的字符串的第一个元素的地址)。
关于c++ - C 风格字符串、指针、数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20861952/