我不太理解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";
我在Version3遇到了麻烦。这里有一个指向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
以前,在“我所知道的”部分,打印指针名称会打印出它所持有的地址。在这里,打印指针名将打印出整个字符串。双引号“Hi you”是否告诉程序:“嘿,我知道你是一个指针,并且已初始化为'H'的位置,但因为我看到这些双引号,所以在内存位置向前移动1个字节,并打印出直到达到\0的所有内容”(char大小为1个字节,因此移动1个字节)。
为什么打印指针会打印出字符串?以前,打印指针名称会打印出它初始化的内存地址。
编辑: cout << &version3
是否打印出“H”的位置还是指针version3
的位置,该指针保存了“H”的内存地址?