简体   繁体   English

打印指针值

[英]Printing pointer values

I wrote the following program to understand the addition of integer values to pointer values. 我编写了以下程序,以了解将整数值添加到指针值。 In my case, the pointers point to integers. 在我的情况下,指针指向整数。 I understand that if p is a pointer to an integer, then p+2 is the address of the integer stored "two integers ahead" (or 2*4 bytes = 8 bytes). 我知道,如果p是指向整数的指针,则p + 2是“前面两个整数”存储的整数的地址(或2 * 4字节= 8字节)。 The program below works as I expect for the integer array, but for a char array it just prints empty lines. 下面的程序按照我对整数数组的预期工作,但对于char数组,它只显示空行。 Could someone please explain to me why? 有人可以向我解释为什么吗?

#include <iostream>

int main() {

    int* v = new int[10];

    std::cout << "addresses of ints:" << std::endl;

    // works as expected
    for (size_t i = 0; i < 10; i++) {
        std::cout << v+i << std::endl;
    }

    char* u = new char[10];

    std::cout << "addresses of chars:" << std::endl;

    // prints a bunch of empty lines
    for (size_t i = 0; i < 10; i++) {
        std::cout << u+i << std::endl;
    }

    return 0;
}

It's because char * has special significance (C strings) so it tries to print it as a string. 这是因为char *具有特殊的意义(C字符串),所以它尝试将其打印为字符串。 Cast the pointers to let cout know what you want: 转换指针以让cout知道您想要什么:

std::cout << (void *)(u+i) << std::endl;

when you print a char* you are printing strings. 当您打印一个char*您正在打印字符串。 So, you are getting junk values. 因此,您将获得垃圾值。 You can cast it to a int to print it. 您可以将其转换为int以进行打印。

std::cout << (int)(u+i) << std::endl;

EDIT from comments : 编辑评论:

As it has been pointed out, a void* cast is better. 正如已经指出的那样, void*类型转换更好。 AFAIK for printing int is fine, but void* is the correct way to do it AFAIK用于打印int很好,但是void*是正确的方法

It worked for me when I converted the pointer value to long long. 当我将指针值转换为long long时,它为我工作。

    std::cout << (long long)(u+i) << std::endl;

You should use long long instead of int if you have a large memory ( > 2 GB) 如果内存较大(> 2 GB),则应使用long long而不是int。

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

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