user1607425
user1607425

Reputation:

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). The program below works as I expect for the integer array, but for a char array it just prints empty lines. 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;
}

Upvotes: 1

Views: 865

Answers (3)

Emad Farag
Emad Farag

Reputation: 46

It worked for me when I converted the pointer value to 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)

Upvotes: 1

Chip
Chip

Reputation: 3316

when you print a char* you are printing strings. So, you are getting junk values. You can cast it to a int to print it.

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

EDIT from comments :

As it has been pointed out, a void* cast is better. AFAIK for printing int is fine, but void* is the correct way to do it

Upvotes: 1

cnicutar
cnicutar

Reputation: 182619

It's because char * has special significance (C strings) so it tries to print it as a string. Cast the pointers to let cout know what you want:

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

Upvotes: 7

Related Questions