Understanding pointers

So I am learning about pointers and I am currently reading my textbook. The textbook gave us this code and I inputted it into my computer using DevC++,and I am getting errors saying that I cant cast char* to long int, short int to long int, float* to long int, double* to long int, and char to long int. Can anyone explain why it works in the book but not on my computer? And as an extra can anyone tell me the necessity of using the actually using pointers for finding the address of variables?
thanks in advanced.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

//This program uses the & operator to determine a 
//variables address.
#include<iostream>
using namespace std;

char letter;
short number;
float amount;
double profit;
char ch;

int main()
{
	//Print address of each variable
	//The cast to long makes addresses print in decimal
	//rather than in hexadecimal
	cout << "Address of letter is:    " << long(&letter) << endl;
	cout << "Address of number is:    " << long(&number) << endl;
	cout << "Address of amount is:    " << long(&amount) << endl;
	cout << "Address of profit is:    " << long(&profit) << endl;
	cout << "Address of ch is:        " << long(&ch)<< endl;
	return 0; 
}
It seems like the textbook assumed that long is at least as big as the size of a pointer, which is not always the case. To make it work the way the book intended you can change long to long long.

 
cout << "Address of letter is:    " << (long long)(&letter) << endl;

Or, if you don't mind printing the address in hexadecimal notation, you can print the pointers directly without converting them to integers first.

 
cout << "Address of letter is:    " << &letter << endl;
Last edited on
Or, if you don't mind printing the address in hexadecimal notation, you can print the pointers directly without converting them to integers first.

For letter and ch, that will give you unexpected results, because cout has an specialised << operator for char * that treats it as if it were a C string.
Last edited on
And as an extra can anyone tell me the necessity of using the actually using pointers for finding the address of variables?

--------
There is no sense in that most of the time. You might use it to debug something, but you would do that using a debugger that TELLS you the address, not code to look it up. If you are doing excessive pointer math, you might do it, but that should be avoided at all costs. If you are doing anything but the most basic pointer math, you probably borked your design (there are exceptions, but you will recognize them when you are at an expert level, for now, those don't matter).

I mean, you can do something like this:
int array[100];
int *p = &array[50];
for(...index < 50)
p[index] = array[index]; //copy the front half of the array to its back half, eg abcd becomes abcdabcd ... and you can do this without pointers, but its a quick example of the sort of SIMPLE pointer manipulation that occasionally comes in handy.

the book example is just showing you how things work, it has little practical value.
Last edited on
And as an extra can anyone tell me the necessity of using the actually using pointers for finding the address of variables?


See my post in this thread for some reasons why pointers are (*) useful:

http://www.cplusplus.com/forum/general/105593/

(*) Or, ar least, were useful. As the language has evolved, better ways to do these things have been introduced, and it's much less common now to need to use primitive pointers in C++.
** just to clarify my post: pointers still have a lot of uses, but viewing the address locations specifically does not. Taking the address of things into a pointer is still important for things like networking/file I/O where you might like to file.write( pointer, number of bytes). or the similar sendto type commands, and any number of library functions out in the wild expect pointers; a tool I use daily can call external programs but it wants C-strings to move text in and out of the external routines...
MikeyBoy wrote:
For letter and ch, that will give you unexpected results, because cout has an specialised << operator for char * that treats it as if it were a C string.


What is the expected unexpected behavior? *scratches head*

Address of letter is:    934791
Address of number is:    934788
Address of amount is:    934784
Address of profit is:    934792
Address of ch is:        934790


Why's long used? Why is it used over int, for example?

And the addresses of these variables are very close.. not what textbooks say about different datatypes being far apart in memory.. no? Is this world really just all a lie?
Last edited on
What is the expected unexpected behavior? *scratches head*

I was talking about the second code snippet, where the addresses weren't cast to long. As would be obvious, if you actually read what I wrote; how would talking about the specialised operater for char* make sense if I was talking about longs? Do at least try to read a post before replying to it.

And the addresses of these variables are very close.. not what textbooks say about different datatypes being far apart in memory.. no?

Um... what? Why wouldn't you expect those memory addresses to be close? Those variables are all created on the stack, so obviously they would all be close together in memory.

I have a feeling you must have radically misunderstood something you've read. Can you show us what you're referring to?
Last edited on
Ah okay, I don't know how that works, but that makes sense, because I don't get output.

Why wouldn't you expect those memory addresses to be close?

I have only ever read one book on C++, that too not fully, and that is Jumping into C++ by Alex Allain.
I'll go through it a bit later to see why I had this impression but maybe I confused with how linear arrays are allocated. Probably the most likely candidate.

But I seriously had that impression and umgh I have no clue why.
arrays are 100% assured to be a single block of memory.
if you say
char *cp = new char(1000)
then you can know that
&cp[0] and &cp[999] are 1000 apart (or 999, ive managed to confuse myself, which isnt hard to do).
this is what an array IS. Its a block of memory, and you move to offsets from it to access the correct bytes, which is what the [] indexing is doing for you.

anything else, not so much.
int x;
double d;
&d and &x could be "anything" **

**sort of. modern OS make an address space for each program and your data will land inside that for non-new-allocated data (the stack). So you know that x and d are going to be within some relatively small distance of each other, since both are on the stack of your program, which is still going to be millions of bytes apart at the extreme ends. There is a fair chance they will be close together, just by nature of how things are done by the OS.

you can also know that variables inside the same class or struct are 'neighbors'. This works a lot like the arrays, but you must be careful as many c++ types like string have a pointer inside. The memory tied to by those pointers is not nearby (unless by chance).
Last edited on
Try this (the constexpr objects would typically be at a different area in memory).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstdint>

template < typename T > std::uintptr_t address_as_number( const T& object )
{ return std::uintptr_t( std::addressof(object) ) ; }

char letter;
const char const_letter = 'A' ;

short number;
const short const_number = 0 ;

float amount;
const float const_amount = 1 ;

double profit;
const double const_profit = 2 ;

#define PPM_PRINT_ADDRESS_AS_NUMBER(var) \
{\
    std::cout << "numeric value of address of '" #var "' is " \
              << address_as_number(var) << '\n' ; \
}

int main()
{
    PPM_PRINT_ADDRESS_AS_NUMBER(letter) ;
    PPM_PRINT_ADDRESS_AS_NUMBER(number) ;
    PPM_PRINT_ADDRESS_AS_NUMBER(amount) ;
    PPM_PRINT_ADDRESS_AS_NUMBER(profit) ;

    std::cout << "-----------------------------\n" ;

    PPM_PRINT_ADDRESS_AS_NUMBER(const_letter) ;
    PPM_PRINT_ADDRESS_AS_NUMBER(const_number) ;
    PPM_PRINT_ADDRESS_AS_NUMBER(const_amount) ;
    PPM_PRINT_ADDRESS_AS_NUMBER(const_profit) ;
}

http://coliru.stacked-crooked.com/a/4b3dda2e24427ba3
Topic archived. No new replies allowed.