【发布时间】:2014-01-18 15:52:43
【问题描述】:
我无法理解 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”的内存地址?
【问题讨论】:
-
"Happy early New Year" 里面的内容有点随意。大声笑
-
我想说将 C 字符串称为“劣于”C++ 字符串有点强,尤其是考虑到一个(通常)是根据另一个实现的。
-
我建议你的新年决心是在发布之前搜索 Web 和 StackOverflow!
-
看看comp.lang.c FAQ,特别是第 4 节(指针)、第 6 节(数组和指针)和第 8 节(字符和字符串)。
标签: c++ c arrays string pointers