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; } 
1

3 Answers 3

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; 
Sign up to request clarification or add additional context in comments.

6 Comments

What you suggested works the way I want, but what is the reason for that?
@curvature Perhaps you loaded the post before I edited ? In C++ character arrays are special; so are pointers to char.
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.
@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.
@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.
|
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

2 Comments

You think casting to int is safe ?
A void * cast would be more appropriate.
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)

Comments