Thread: Declaring a pointer, int *ptr vs int ptr

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    204

    Declaring a pointer, int *ptr vs int ptr

    The following code works
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int a = 1;
    	int *b;
    	
    	b = &a;
    	
    	cout << " a is:" << a  << endl;
    	cout << " &a is:" << &a  << endl;
    	cout << " b is:" << b  << endl;
    	cout << " *b is:" << *b  << endl;
    	
    	return 0;
    }
    If I change "int *b" to "int b," as shown below, then the code does not compile. Why is this? What exactly does the statement "int *b declare?"
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int a = 1;
    	int b;
    	
    	b = &a;
    	
    	cout << " a is:" << a  << endl;
    	cout << " &a is:" << &a  << endl;
    	cout << " b is:" << b  << endl;
    	cout << " *b is:" << *b  << endl;
    	
    	return 0;
    }

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    int* b declares a pointerr to int;

    b is a variable able to store the address of some int variable

    b = &a; takes the address of a and stores it in the b
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    125
    "int *b;" declares a pointer that can point to an object of type int.
    "int b;" declares an int (a signed integer, generally 16 to 64 bits depending on your compiler and environment). It's not a pointer, and certainly not a pointer to another int.
    Have you read the tutorials on pointers on the main site?
    (edit: vart beat me to it)
    Typing stuff in Code::Blocks 8.02, compiling stuff with MinGW 3.4.5.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 11-30-2007, 03:51 AM
  2. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM
  3. Replies: 2
    Last Post: 03-24-2006, 08:36 PM
  4. Converted from Dev-C++ 4 to Dev-C++ 5
    By Wraithan in forum C++ Programming
    Replies: 8
    Last Post: 12-03-2005, 07:45 AM
  5. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM