指针的地址

3

我是一个编程新手。我遇到了一个问题,无法找到自己能够理解的答案。我想通过使用C++和C来查找指针的地址,但是两个结果是不同的,尽管它们有一些相似的数字。它们仍然是相同的地址吗?

adress of g is :0018F9C4
address of g is: 0018F9D3

这是我的代码:

#include<iostream>
#include<stdio.h>
void main()
{
    char g = 'z';
    char*p;

    p = &g;

    std::cout << "adress of g is :" << &p;
    printf("\naddress of g is: %p", p);
}

printf语句中的“&”在哪里? - Olayinka
1
当你执行 &g 时,你会得到一个指向 g 的指针。当你执行 &p 时会发生什么?(提示:你不会得到一个指向 g 的指针) - Some programmer dude
void main() 是错误的。请使用 int main() - Simple
5个回答

7

这行显示p标签的地址。

std::cout << "address of p is :" << &p;

这一行显示了地址p内,即g的地址

printf("\naddress of g is: %p", p);

"通常结果会有所不同。"
"请尝试:"
std::cout << "address of g is :" << static_cast<void*>(p);
printf("\naddress of g is: %p", p);

7
p的类型是char*。你可能需要将其转换为void*,以便ostream不将其解释为C字符串。 - Roland W

1
这个例子可能更好地展示它:

#include<iostream>
#include<stdio.h>
int main()
{
    char g = 'z';
    char*p = &g;
    std::cout << "adress of g is :" << static_cast<void*>(p);
    std::cout << "\nadress of p is :" << &p;
    return 0;
}

演示

static_cast<void*>(p) 是将一个 char* 转换为 void*,这是出于历史原因。在 C 语言中,char* 被用作 string,但实际上它是一个指针。因此,<< 运算符 将把它视为一个值而不是一个指针。因此,这里的技巧是将其转换为另一种指针类型,这样 << 运算符 将打印其实际值,即 g 的地址。

现在,&pp 的地址,而不是 g 的地址。换句话说,它是存储 g 的地址的位置的地址。

(g=='z') is True
(&g==p) is True
(*p==g) is True

(&p==p) is False
(&g=&p) is False

1

在使用std::cout时,您打印出&p...即p本身的地址。在printf行中,您打印出p的值..没有&p

当然,这是不同的。

您应该使用

std::cout << "adress of g is :" << (void *)p;
printf("\naddress of g is: %p", p);

为什么您要混用cout和printf?


1
你需要记住,指针的地址指针所指向的地址是两个不同的概念。

&p --> "P"的地址 p --> 指针所指向的"g"的地址


0

答案: 不,它们不是相同的地址,这很明显因为它们的值是不同的 - 指向同一位置的程序内存地址将始终相同。

解释:
(tl;dr - &pp 的地址,而不是 g 的地址)

char g = 'z' 做了你所期望的事情 - 创建一个文字常量,并确保它在程序执行期间的某个地方存在于内存中。 char*p; p = &g;(可以缩短为char*p = &g)再次做了你所期望的事情,将数据g的内存地址提供给名为p的变量 ~ 请注意,p也是一个变量,因此必须保存在内存中!

您的程序中的错误发生在执行的最后两行:

std::cout << "adress of g is :" << &p;
printf("\naddress of g is: %p", p);

第一行(使用std :: cout)将呈现p地址,如先前所述,p是指针,但指针与任何其他变量没有区别-它只是存储在内存中的数据。因此,在这一点上,您正在创建一个指向指针临时 -也称为char **

然而,第二行执行您期望的操作,输出存储在p中的内存地址。 正确的程序应该如下所示。

#include<iostream>
#include<stdio.h>
void main()
{
    char g = 'z';
    char*p = &g;


    std::cout << "adress of g is :" << (int)p; //optionally for C++11 use static_cast<int>
    printf("\naddress of g is: %p", p);
}

你也可以尝试在这个示例上使用调试器!

#include<iostream>
#include<stdio.h>
#include<cstdint>
void main()
{
    char g = 'z';
    char*p = &g;

    //THIS ASSUMES 32-bit! Note on 64bit systems a pointer is 64-bit, (you can conclude the result for an 8bit or 16bit addressing model)
uint32_t P_value = (uint32_t)p;

    std::cout << "adress of g is :" << P_value;
    printf("\naddress of g is: %p", p);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接