简体   繁体   中英

Why does my pointer to a char only get the first character in it?

I initialized a char and a pointer, and then point it to the char. But I found that only the first character in the char was passed into the pointer. How could this be? Appreciate any advice!

    char p[]="This is a long char.";
    std::cout<<sizeof(p)<<"\n";
    char *ptr=p;
    std::cout<<*ptr<<"\n";

Got:

21
T
Program ended with exit code: 0

When checking the value of variables I noticed that:

ptr=(char *) "This is a long char."
*ptr=(char) 'T'

Why is the ptr holding the whole char but the content in it is only the first character? Isn't this the opposite of what we call a pointer? Got really confused...

When you said:

std::cout<<*ptr...

you dereferenced ptr , which gives you the (first) character that ptr is pointing to.

flyingCode's answer shows you how to print the entire string.

In C++, an array is just like multiple variables grouped together, so they each have a memory address, but they are one after another.

So, the pointer is pointing at the address of the first element, and the other elements are in the adresses right after that in order.

When you use the * operator on a pointer, it references the contents of the memory address the pointer is pointing to.

If you wanted to access another element of the array using this, you would use *(ptr + 5) to offset the memory address.

When you use the variable name alone, the language just does the offset for you and gets all the contents of the array. The pointer doesn't know the length of the array, but it can find the end of it, because char arrays always end with a null character (\\0).

ran your code in repl and changing it to the code below worked :D

  char p[]="This is a long char.";
  std::cout<<sizeof(p)<<"\n";
  char *ptr=p;
  std::cout<<ptr<<"\n"; //notice no *

I recommend you use std::string rather than c-strings unless you have a specific need for them :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM