单个结构数据成员的奇怪指针地址 [英] Weird Pointer Address for Individual Struct Data Member

查看:81
本文介绍了单个结构数据成员的奇怪指针地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天观察到一些奇怪的行为,代码如下:

I observe some weird behavior today , the code is as follow :

代码:

#include <iostream>

struct text
{
    char c;
};

int main(void)
{
    text experim = {'b'};
    char * Cptr = &(experim.c);

    std::cout << "The Value \t: " << *Cptr << std::endl ;
    std::cout << "The Address \t: " << Cptr << std::endl  ; //Print weird stuff

    std::cout << "\n\n";

    *Cptr = 'z';   //Attempt to change the value

    std::cout << "The New Value \t: " << *Cptr <<std::endl ;
    std::cout << "The Address \t: " << Cptr << std::endl ; //Weird address again

    return 0;
}

问题:

1.)我唯一的问题是,为什么上述代码的cout theAddress会出现一些奇怪的值?

The Question :

1.) The only question I have is why cout theAddress for the above code would come out some weird value ?

2.)为什么我仍然可以通过取消引用具有奇怪地址的指针来更改成员c的值?

2.)Why I can still change the value of the member c by dereferenncing the pointer which has weird address ?

谢谢.

推荐答案

考虑修复如下代码:

std::cout << "The Address \t: " << (void *)Cptr << std::endl ;

有一个std::ostream& operator<< (std::ostream& out, const char* s );需要一个char*,因此您必须转换为void*来打印地址,而不是它指向的"字符串"

There's a std::ostream& operator<< (std::ostream& out, const char* s ); that takes a char* so you have to cast to void* to print an address, not a string it "points" to

这篇关于单个结构数据成员的奇怪指针地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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