1

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;
}
  • possible duplicate of [why does my pointer output a string and not a memory address? c++](http://stackoverflow.com/questions/7788639/why-does-my-pointer-output-a-string-and-not-a-memory-address-c) – chris Aug 23 '12 at 21:11

3 Answers3

7

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;
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • What you suggested works the way I want, but what is the reason for that? –  Aug 23 '12 at 21:12
  • @curvature Perhaps you loaded the post before I edited ? In C++ character arrays are special; so are pointers to `char`. – cnicutar Aug 23 '12 at 21:12
  • Actually no, I haven't. I'm just trying to understand why casting a char* to a void* works. I do not really understand what a void* is. –  Aug 23 '12 at 21:14
  • @curvature Ah. A `void *` is a pointer that can hold any object type. In this case it serves as an indication to `cout` telling it to treat `u + i` *as a pointer*, not as a string. Casting it away from `char *` makes `cout` pick a different overload that happens to print the address. – cnicutar Aug 23 '12 at 21:15
  • Thank you. Also, I initialized u as char* u = "abcdefghij"; and the output made your comment entirely clear. –  Aug 23 '12 at 21:16
  • 2
    @curvature, FFR, that should be `const char *` (or `std::string` since this is C++). The contents are read-only, and you should reflect that in the variable's type. – chris Aug 23 '12 at 21:28
1

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

Chip
  • 3,226
  • 23
  • 31
1

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)

Emad Farag
  • 46
  • 2