【发布时间】:2013-12-27 04:38:26
【问题描述】:
我正在自学 C++,但我对指针有点困惑(特别是在以下源代码中)。但首先,我继续向您展示我所知道的(然后将代码与此进行对比,因为我觉得好像存在一些矛盾)。
我知道的:
int Age = 30;
int* pointer = &Age;
cout << "The location of variable Age is: " << pointer << endl;
cout << "The value stored in this location is: " << *pointer << endl;
指针保存内存地址。使用间接(取消引用)运算符(*),您可以访问存储在指针的内存位置中的内容。关于本书中的代码,我无法理解......
cout << "Enter your name: ";
string name;
getline(cin, name); //gets full line up to NULL terminating character
int CharsToAllocate = name.length() + 1; //calculates length of string input
//adds one onto it to adjust for NULL character
char* CopyOfName = new char[CharsToAllocate];
// pointer to char's called CopyOfName, is given the memory address of the
//beginning of a block
//of memory enough to fit CharsToAllocate. Why we added 1? Because char's need a
//NULL terminating character (\0)
strcpy(CopyOfName, name.c_str()); //copies the string name, into a pointer?
cout << "Dynamically allocated buffer contains: " << CopyOfName << endl;
delete[] CopyOfName; //always delete a pointer assigned by new to prevent memory leaks
输出:
Enter your name: Adam
Dynamically allocated buffer contains: Adam
上面代码中的cmets就是我的cmets。我的问题从strcpy 开始。为什么name.c_str() 被复制到指针CopyOfName 中?这是否意味着所有字符串都是必不可少的指针?所以喜欢
字符串测试=“你好世界”;
实际上是指向存储“H”的内存位置的指针吗?
接下来,为什么在打印输出语句中使用CopyOfName 而不是*CopyOfName?指针保存内存地址?使用*CopyOfName 将打印出内存位置的内容。我在 Code::Blocks 中试过这个,如果输入文本是“Hello World”。在打印输出语句中使用*CopyOfName 只会给出“H”。这是有道理的,因为当我声明我需要一个带有“新”事物的内存块时,这实际上返回了一个指向动态分配的内存块第一部分的指针。
我可以协调这一点的唯一方法是,如果一个字符串实际上是一个指针。
string testing = "Confused";
cout << testing << endl;
会打印出“困惑”这个词
但是,如果我尝试编译
string testing = "Confused";
cout << *testing;
我收到一条错误消息。
基本上,总结一下我的问题,我试图用strcpy 和cout 语句来理解代码。
【问题讨论】:
-
附带说明,没有“
NULL终止字符”之类的东西。然而,有一个“NUL”('\0')字符可能就是你的意思。