C++ char 和 char*(指针)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12877120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:43:14  来源:igfitidea点击:

char and char* (pointer)

c++pointerschardereferencetype-mismatch

提问by Iburidu

I would like to understand how pointers work, so i created this small program. first of all i create a p pointer, which points to a char.

我想了解指针是如何工作的,所以我创建了这个小程序。首先我创建 ap 指针,它指向一个字符。

The first question is at this point. If i create a pointer, the value of it is a memoryaddress (if i point it to a non-pointer object), but this time it is "haha" in my example. Why does it work this way in char*? And how i can add value to it with cin >> p?

第一个问题是在这一点上。如果我创建一个指针,它的值是一个内存地址(如果我将它指向一个非指针对象),但这次在我的例子中它是“哈哈”。为什么它在 char* 中以这种方式工作?以及如何使用 cin >> p 为其增加价值?

My second question is that, i created a q char, which has the value of the *p pointer at the point i created it. BUT its value and address are "h" too, but why? It must be the memory address of this char object! It's pointless :D (mingw - gcc)

我的第二个问题是,我创建了 aq char,它在我创建它时具有 *p 指针的值。但是它的值和地址也是“h”,但为什么呢?一定是这个char对象的内存地址!这是毫无意义的 :D (mingw - gcc)

#include <iostream>

int main() 
{
 /* char *p;
    cin >> p;                      //forexample: haha */

    char * p = "haha";
    char q = *p;
    std::cout << "&q = " << &q << std::endl;   //&q = h
    std::cout << "q  = " <<  q << std::endl;   //q = h

    return 0;
}

MORE: If i allocate memory first with char a[100]; char *p=a; then &q = h???, so "h" and some mess. but it should be a memoryaddress! and my question is, why is not it address then?

更多:如果我先用 char a[100] 分配内存;字符 *p=a; 然后&q = h???,所以“h”和一些混乱。但它应该是一个内存地址!我的问题是,为什么不解决呢?

采纳答案by PiotrNycz

Think of char* p;as of address in memory. You did not initialize this pointer so it does not point to anything, you cannot use it.

想想char* p;内存中的地址。你没有初始化这个指针,所以它不指向任何东西,你不能使用它。

To be safe always:
either initialize pointer to zero:

为了始终安全:
要么将指针初始化为零:

char *p = 0; // nullptr in C++11

or initialize to some automatic

或初始化为一些自动

void foo() {
  char a[100];
  char *p = a;
}

or global memory:

或全局内存:

char a[100];
void foo() {
  char *p = a;
}

or get dynamic memory:

或获取动态内存:

char* p = new char [100];

Then you can use p (if not NULL) to read data and to read from p...

然后您可以使用 p (如果不是 NULL)来读取数据并从 p...



For your misunderstaning of operator >> (std::istream&, char* p). This operator expects that ppoints to some memory (automatic,global,dynamic - no matter) - it does not allocate memory by itself. It just reads characters from input stream until whitespace and copy it to the memory pointed by p- but pmust already points to some memory.

对于您对operator >> (std::istream&, char* p). 此运算符期望p指向某个内存(自动、全局、动态 - 无论如何) - 它不会自行分配内存。它只是从输入流中读取字符直到空格并将其复制到指向的内存p- 但p必须已经指向某个内存。



For taking address of char q;. Of course you can take address of q: &q, and it type is char* p. But &qis different that p, and this q=*pjust copies first character pointed by pto q, it cannot change address of q- its address is unchangeable. For cout << &q- operator << (ostream&, char* p)expects that ppoints to NULL terminated string - and &qpoints to memory containing "H"but what is after this character no one knows - so you will get some garbage on screen. Use cout << qto print single character.

用于取地址char q;。当然你可以取地址q&q,它的类型是char* p。但是&q是不同的p,这q=*p只是复制的第一个字符指出通过pq,它不能改变地址q-其地址是不变的。For cout << &q-operator << (ostream&, char* p)期望p指向 NULL 终止的字符串 - 并&q指向包含"H"但没有人知道这个字符之后的内存- 所以你会在屏幕上看到一些垃圾。使用cout << q打印单个字符。

回答by Hisham

First thing to learn and always remember about pointers is to make sure to allocate memory for them, otherwise your program won't run properly.

关于指针,要学习并始终记住的第一件事是确保为它们分配内存,否则您的程序将无法正常运行。

Your code should actually be modified as follows to allocate memory so that "cin" can write the user input into the allocated memory:

您的代码实际上应该修改如下以分配内存,以便“cin”可以将用户输入写入分配的内存:

int main() {
    char *p = new char[1024];      // allocate memory so cin
    cin >> p;                      //forexample: haha
    char q = *p;
    cout << "&q = " << &q << endl; 
    cout << "q = " << q << endl;   
    return 0;
}

Now, a character pointer is a variable pointing to a position in memory holding a set of characters (not necessarily one character, maybe more than one, maybe none as in the case of the special value null), while a character variable is actually holding a single character (not a set of characters).

现在,字符指针是指向内存中某个位置的变量,其中包含一组字符(不一定是一个字符,可能不止一个,也可能没有,就像特殊值 null 的情况一样),而字符变量实际上是保存单个字符(不是一组字符)。

The basic operators when dealing with pointers is the &(address of) and *(value at). The & retrieves the address of a variable, so if we have [char q;] then [&q] would be a character pointer. On the other hand, the * retrieves the value at the given pointer, so if we have [char *p;] then [*p] would be the character in memory at which p is pointing.

处理指针时的基本运算符是 &(address of) 和 *(value at)。& 检索变量的地址,所以如果我们有 [char q;] 那么 [&q] 将是一个字符指针。另一方面, * 检索给定指针处的值,因此如果我们有 [char *p;] 那么 [*p] 将是 p 指向的内存中的字符。

Now back to your example, comments inline for illustration

现在回到您的示例,内联注释以供说明

int main() {
    // allocate a place of 1024 character in memory
    // and let p points to that place
    char *p = new char[1024];      

    // call cin to read input from the user and save
    // it in memory at the location pointed to by p
    // NOTE: cin would put an extra NULL character 
    // at the end to terminate the string
    cin >> p;                      //forexample: haha

    // Now p would be pointing to a piece of memory like this
    // [h] [a] [h] [a] [
#include <iostream>
using namespace std;
] // use the value at operator to de-reference the pointer // p, the result would be a single character which // will be the first character in memory p is pointing at char q = *p; // printing the value of (the address of q) // Note you have a problem here as cout will // be handling the memory starting at the address // of q as a string while it is not, so you // will get a string starting with "h" and followed // by whatever is there in memory by the time of execution cout << "&q = " << &q << endl; // printing the value of the character q cout << "q = " << q << endl; return 0; }

I hope it helps

我希望它有帮助

回答by Keith Thompson

You should have something like:

你应该有类似的东西:

int main() {
    char *p;

at the top of your program. Or could omit the usingand refer to std::cinand std::cout.

在你的程序的顶部。或者可以省略usingand 引用std::cinand std::cout

p = new char[100];

pis a pointer, but you haven't initialized it, so it could point anywhere or nowhere. You need to initialize it, for example with:

p是一个指针,但你还没有初始化它,所以它可以指向任何地方或任何地方。您需要初始化它,例如:

    cin >> p;                      //forexample: haha

...

...

    char q = *p;
    cout << "&q = " << &q << endl; //&q = h

This is ok ifyou've initialized pto point somewhere -- except that you can overflow the buffer it points to if you enter too much data. That's ok for a simple test program like this, but in practice you'll want to take measures to avoid it.

这是确定的,如果你已经初始化p,以点的地方-除了你可以溢出它指向如果输入太多的数据缓冲区。对于像这样的简单测试程序来说这没问题,但在实践中您需要采取措施来避免它。

count << "&q = " << (void*)&q << endl;

&qis of type char*, a pointer to char. Sending a char*value to coutdoesn't print the value of the pointer (a memory address); it prints the string that it points to. (Though I'm getting some odd results when I run it myself; I may be missing something.) If you want to see the pointer value, cast it to void*:

&q是 类型char*,指向char. 发送一个char*值到cout不打印指针的值(内存地址);它打印它指向的字符串。(虽然我自己运行时得到了一些奇怪的结果;我可能遗漏了一些东西。)如果您想查看指针值,请将其转换为void*

    cout << "q = " << q << endl;   //q = h

(Or you could use one of the C++-specific casts; I'm not sure which is best.)

(或者您可以使用特定于 C++ 的强制转换之一;我不确定哪个是最好的。)

    return 0;
}

Here qis just a char, so this prints its value as a character: h.

这里q只是一个char,因此将其值打印为字符:h

char *p = "some text";

回答by dev65

the string literate will be stored in .rdata section which will be read only so reading into it with std cin would crash the program

字符串 literate 将存储在 .rdata 部分中,该部分将被只读,因此使用 std cin 读入它会使程序崩溃

the second thing , when you write this :

第二件事,当你写这个时:

char q = *p;

then the pointer p points to an allocated and read only memory , as the rdata section will be surely allocated and prepared by the windows loader , but as I said .rdata can't be modified

然后指针 p 指向一个已分配的只读内存,因为 rdata 部分肯定会由 windows 加载程序分配和准备,但正如我所说的 .rdata 不能修改

then when you write this :

然后当你写这个时:

++p;
q = *p;

you only assign q to the first char in p as * returns the value the pointer is currently pointing to so if you tried this :

您只将 q 分配给 p 中的第一个字符,因为 * 返回指针当前指向的值,因此如果您尝试这样做:

    int arraySize;
    cin>>arraySize;
    char *a=new char[arraySize];
    cin >> a;

the q will hold 'a' not 'h' as the pointer is an address that points to a some chars beginning from the first so increasing by one it will make the pointer point to the second char and q will hold this value

q 将保存“a”而不是“h”,因为指针是指向从第一个字符开始的一些字符的地址,因此增加一个将使指针指向第二个字符,而 q 将保存该值

回答by Nagendra Reddy

Better way to do it is:

更好的方法是:

##代码##