指针和字符串C ++ [英] Pointers and Strings C++

查看:176
本文介绍了指针和字符串C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我教自己C ++,我有点困惑指针(特别是在下面的源代码)。但首先,我继续向你展示我所知道的(然后将代码与这种对比,因为我觉得有一些矛盾。)



我知道:

  int Age = 30; 
int * pointer =& Age;

cout<< 变量Age的位置是:<指针<< endl;
cout<< 存储在该位置中的值是:< *指针<< endl;

指针保存内存地址。使用间接(解引用)运算符(*),可以访问存储在指针的内存位置的内容。

  cout<< 输入你的名字: ; 
string name;
getline(cin,name); //得到满线的NULL终止字符

int CharsToAllocate = name.length()+ 1; //计算字符串输入的长度
//添加一个字符来调整NULL字符
char * CopyOfName = new char [CharsToAllocate];
//指向char的名称为CopyOfName的指针,给出了
的内存地址//开始一个块
//的内存,足以适合CharsToAllocate。为什么我们添加1?因为char的需要一个
// NULL结束符(\ 0)

strcpy(CopyOfName,name.c_str()); //将字符串名称复制到指针中?

cout<< 动态分配的缓冲器包含:< CopyOfName<< endl;
delete [] CopyOfName; //总是删除由new分配的指针以防止内存泄漏

输出:



输入您的姓名:Adam
动态分配的缓冲区包含:Adam

上面代码中的注释是我的注释。我的问题从 strcpy 开始。为什么 name.c_str()被复制到指针 CopyOfName ?这是否意味着所有字符串是必要的指针?所以像
string testing =Hello world;
实际上是指向存储H的内存位置的指针?



接下来,为什么在print out语句中使用 CopyOfName ,而不是 * CopyOfName ?指针保存内存地址?使用 * CopyOfName 将打印出内存位置的内容。我试过这个在Code :: Blocks和如果输入文本是Hello World。在print out语句中使用 * CopyOfName 只会给出一个H。这是有意义的,因为当我声明我需要一个内存块与'new'的东西,这实际上返回一个指针动态分配的内存块的第一部分。



  string testing =Confused;如果一个字符串实际上是一个指针, 
cout<<测试< endl;

会打印出Confused字样



但是,如果我尝试编译

  string testing =Confused 
cout<< *测试;

我收到错误讯息。



基本上,总结我的问题,我试图理解代码与 strcpy cout 语句。 p>

解决方案

看来你明白什么是C风格的字符串,但总而言之,它们只是内存中的字符数组由一个nul字符 \0 终止。通常,它们通过指向字符串中第一个字母的 char * 引用。当它们被打印时,通常从第一个开始打印字符串的字符,并且当到达 \0 终止符时停止打印(或复制等)。



std :: string 是一个类(通常)包装一个C风格的字符串。这意味着 std :: string 对象(通常)具有用于实现其功能的私有C风格字符串。函数 std :: string :: c_str()返回一个指向这个基本C风格字符串的指针。



让我们假设 char * str; 指向一个C风格的字符串。如果你试图运行 cout<< * str<< endl; ,你注意到只有第一个字符被打印。这是因为C ++的函数重载。 * str 的数据类型为 char ,因此 char cout 的版本,并忠实打印单个字符 * str 。为了与C风格字符串兼容,使用 char * 作为参数的 cout 版本将指针视为用于打印的C样式字符串。如果你 cout 一个 int * ,例如,底层 int 因为你尝试引用 std :: string 对象失败的原因是,它不是一个指针。您可以取消引用 std :: string :: c_str()的返回值,然后返回第一个 char



相关:如何std :: string implemented?


I'm teaching myself C++ and I'm a bit confused about pointers (specifically in the following source code). But first, I proceed with showing you what I know (and then contrasting the code against this because I feel as if there are some contradictions going on).

What I know:

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;

Pointers hold memory addresses. Using the indirection (dereference) operator (the *), you can access what is stored in memory location of the pointer. Onto the code in this book I'm having trouble understanding...

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

Output:

Enter your name: Adam
Dynamically allocated buffer contains: Adam

The comments in the above code are my comments. My problem begins with strcpy. Why is name.c_str() copied into a pointer CopyOfName? Does this mean that all strings are essential pointers? So like string testing = "Hello world"; Is actually a pointer pointing to the memory location where "H" is stored?

Next, why is it in the print out statement using CopyOfName and not *CopyOfName? Pointers hold memory addresses? Using *CopyOfName would print out the contents of the memory location. I tried this in Code::Blocks and if the input text was "Hello World." Using *CopyOfName in the print out statement would just give an "H". This makes sense since when I declared that I needed a memory block with the 'new' thing, this actually returns a pointer to the first part of the dynamically allocated memory block.

The only way I can reconcile this is if a string is actually a pointer.

string testing = "Confused";
cout << testing << endl;

would print out the word "Confused"

However, if I try to compile

string testing = "Confused";
cout << *testing; 

I get an error message.

Basically, to summarize my question, I'm trying to understand the code with strcpy and the cout statement.

解决方案

It seems like you understand what C-style strings are, but to summarize, they are just arrays of characters in memory, by convention terminated by a nul character \0. Usually they are referenced via a char* pointing to the first letter in the string. When they are printed, typically the characters of the string are printed starting from the first, and printing (or copying, etc.) stops when the \0 terminator is reached.

An std::string is a class that (typically) wraps a C-style string. This means that a std::string object (typically) has a private C-style string that is used to implement its functionality. The function std::string::c_str() returns a pointer to this underlying C-style string.

Let's suppose that char *str; points to a C-style string. If you attempt to run cout << *str << endl;, you noticed that only the first character is printed. That is because of C++'s function overloading. The data type of *str is char, so the char version of cout is called and faithfully prints the single character *str. For compatibility with C-style strings, the version of cout that takes a char* as an argument treats the pointer as a C-style string for printing purposes. If you cout an int*, for example, the underlying int will not be printed.

Edit: Another comment:

The reason that your attempt to dereference an std::string object failed is that, indeed, it is not a pointer. You could dereference the return value of std::string::c_str(), and you would get back the first char of the string.

Related: How is std::string implemented?.

这篇关于指针和字符串C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆