变量值及其地址使用C++中的指针

variable value and its address using pointers in C++

本文关键字:C++ 指针 地址 变量值      更新时间:2023-10-16

我在理解指针方面遇到了一些问题。在下面的代码中,我尝试用两种方式打印变量的地址,一种是使用地址运算符,另一种是用指针:

#include<iostream>
using namespace std;
int main (void)
{
    int x = 10;
    int *int_pointer;
    int_pointer = &x;
    cout << "x address=" << &x << endl;
    cout << "x address w pointer=" << int_pointer << endl;
    return 0;
}
x address = 0028FCC4
x address w pointer = 0028FCC4

这是意料之中的事。但当我做同样的事情,但现在使用字符类型变量时,我会得到一些垃圾输出:

#include<iostream>
using namespace std;
int main(void)
{
    char c = 'Q';
    char *char_pointer;
    char_pointer = &c;
    cout << "address using address operator=" << &c << endl;
    cout << "address pointed by pointer=" << char_pointer << endl;
    return 0;
}
address using address operator=Q╠╠╠╠£åbªp é
address pointed by pointer=Q╠╠╠╠£åbªp é

我不知道为什么会发生这种事。提前感谢。

C++库重载<lt;运算符。(char*)就是其中之一。Cout正在尝试打印一个字符串,一个以null字符结尾的字符数组。

只需投射指针:

cout << "address pointed by pointer" << ( void* )char_pointer << endl;

cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl;

它打印出垃圾的原因是因为你的char没有null终止符,这意味着程序会一直搜索一个,直到,在这个过程中,它会打印出它找到的任何东西。您看到的文本是ASCII,但被ostream误解的地址引用。要获取内存中的地址,可以使用隐式转换或static_cast。我更喜欢后者:

cout << "address pointed by pointer=" << static_Cast<void*>(char_pointer) << endl;

就像2501所说的,用不同的措辞,&c,因为c是char,等于char *,所以它将尝试打印,直到隐式或显式放入到std::cout的字符数组中的新行字符'',这样流就知道字符数组的末尾在哪里。

所以,是的,像2501说的那样使用(void*)。