Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is being printed? C++ pointer to an integer

Tags:

c++

pointers

So I have the following (very simple) code:

int* pInt = new int(32);

std::cout<< pInt << std::endl;  //statement A
std::cout<< *pInt << std::endl; //statement B
std::cout << &pInt << std::endl; //statement C

So here's what I think I am doing (I have learned that in C++ I am rarely ever doing what I think I am doing):

  1. Creating a pointer to an integer and calling it pInt
  2. statementA prints the address of the value '32'
  3. statementB prints the integer value that is being pointed to by my pointer (which is done because I dereference the pointer, thus giving me access to what it is pointing to).
  4. statementC prints the address of the pointer itself (not the address of the integer value '32').

Is all of this correct?

like image 661
LunchMarble Avatar asked May 12 '11 19:05

LunchMarble


People also ask

What is pointer to integer in C?

A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable.

How do I print a pointer to an int?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

What do you mean by pointer to a pointer to integer?

Pointers are just memory address. So a pointer to an int means a variable whose value is the memory address of an int, and a pointer to a pointer to an int means a variable whose value is the memory address of a pointer to int, and the value of that pointer to int is a memory address of an int.

Can we assign pointer to integer?

No, it is no valid to assign a pointer to an integer.


1 Answers

Your second statement is wrong. You allocate a new int off the heap. The compile-time constant "32" does not have an address, and therefore you cannot take it. You create an int whose value is 32. This is not the same thing.

int* pInt1 = new int(32);
int* pInt2 = new int(32);

pInt1 and pInt2 are not equal.

Oh, one last thing- C++ is a pretty strongly typed language, and it's pretty unnecessary to prefix variable names with type data. This is called Hungarian Notation, it's very common in Microsoft C libraries and samples, but generally unnecessary here.

like image 86
Puppy Avatar answered Sep 20 '22 13:09

Puppy