Tutorial - C / C++ - Pointers


Coding Friends Tutorial Index - > C / C++

Author Ian - Tutorial Posts = 62
Pointers are pointers to memory, the variable that is defined as a pointer still holds the same area in memory as the type of the pointer e.g. char and int are of different size in memory, just do a cout << sizeof(char) << “ “ << sizeof(int); to find out.

The actually pointer holds the address of the variable it is pointing to, e.g.

The value variable

Value = 10, address within the memory for value = 4

The pointer

ValuePointer = 4 (the address of the value), address within the memory = 200

The valuepointer actually equals 4, the memory of the value variable, if you use the * (pointer) then you will get the value pointed to, 10, and if you use the & (address) you will get 200 which is the place in memory where the valuepointer is placed in memory.

For example

int main()
{
       int value1 = 10;              
       int *valp = &value1;       // equals the memory address of value1

       std::cout << "Value 1 = " << value1 << " address = " << &value1 << "\n";
       std::cout << "Value p = " << *valp << " address = " << &valp << " pointed to memory " << valp << "\n";
       std::cout << "The value p pointerd to memory is the same as the memory address as value 1\n";
       std::cout << "The value p = the pointerd memory value that is assoicated with the value that is in valp (address of memory)\n";

       (*valp)++;              // correct increament the value that is pointed to by the address held by vapl
       std::cout << "Value 1 = " << value1 << " address = " << &value1 << "\n";
       std::cout << "Value p = " << *valp << " address = " << &valp << " pointed to memory " << valp << "\n";

       *valp++;              // incorrect will increament the address that is held valp by sizeof(int) (usually 4)
       std::cout << "Value 1 = " << value1 << " address = " << &value1 << "\n";
       std::cout << "Value p = " << *valp << " address = " << &valp << " pointed to memory " << valp << "\n";

       return 0;
}
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search