Declaring a pointer, int *ptr vs int ptr

This is a discussion on Declaring a pointer, int *ptr vs int ptr within the C++ Programming forums, part of the General Programming Boards category; The following code works Code: #include <iostream> using namespace std; int main() { int a = 1; int *b; b ...

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

    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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    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
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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, 01: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, 06:20 AM

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