简体   繁体   English

如何在没有指针的情况下存储变量的地址

[英]How to store the address of the variable without pointer

how can we store the address of the variable without using the pointer?我们如何在不使用指针的情况下存储变量的地址?

#include<stdio.h>
int main ()
{
    double sum;
    double x= &sum;

    printf("\n %lf",x);
}

By definition, a pointer is an object that stores the address of another.根据定义,指针是存储另一个地址的 object。 How can you store something without using the appropiate storage variable for that kind of data?如果不使用适当的存储变量来存储此类数据,如何存储? There are no other objects to store addresses, so what do you suggest?没有其他对象可以存储地址,那么您有什么建议?

If you just want to print the address to stdout , just do the following:如果您只想将地址打印到stdout ,只需执行以下操作:

    printf("%p\n", &sum);

The format specifier %p allows you to pass a pointer, and you can use &sum directly to pass the value of the address of sum .格式说明符%p允许您传递一个指针,您可以直接使用&sum来传递sum的地址值。

You did it almost right.你做的几乎是对的。 But you stored it in a double , the memory address of a variable can be 4 bytes, or 8 bytes, depending on the implementation.但是您将它存储在double中,变量的 memory 地址可以是 4 个字节或 8 个字节,具体取决于实现。 You should always cast to a wider type though.不过,您应该始终转换为更广泛的类型。 Right now, storing it in a double may cause loss of information.现在,将其存储在double中可能会导致信息丢失。

You'll need to use a data type wide enough.您需要使用足够广泛的数据类型。 You could use an unsigned long long , however for cross platform compatibility, I recommend using uint64_t from stdint.h instead.您可以使用unsigned long long ,但是为了跨平台兼容性,我建议使用stdint.h中的uint64_t And also the accompanying inttypes.h .还有随附的inttypes.h

#include<stdio.h>
#include<stdint.h>
#include<inttypes.h>

int main()
{
    double sum;
    uint64_t x = (uint64_t) &sum;

    printf("%" PRIx64 "\n", x);
}

This ensures that you use an unsigned 64 bit (8 byte) variable so you do not lose information.这可确保您使用无符号的 64 位(8 字节)变量,这样您就不会丢失信息。

Also print using the PRIx64 format specifier for getting output in 64 bit hexadecimal form.还使用PRIx64格式说明符打印以获取 64 位十六进制格式的 output。

Do note however, this is only good for printing the address, and address only.但是请注意,这仅适用于打印地址,并且仅适用于地址。 This really does not serve any practical purpose.这确实没有任何实际用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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