KEMBAR78
Revision On Pointers and Structures in C++ | PDF | Pointer (Computer Programming) | Computer Data
0% found this document useful (0 votes)
38 views42 pages

Revision On Pointers and Structures in C++

The document discusses pointers in C++. A pointer stores the address of another variable. Pointer operators like & and * are explained. Declaring and accessing pointers as well as pointer arithmetic are also covered.

Uploaded by

seadamoh80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views42 pages

Revision On Pointers and Structures in C++

The document discusses pointers in C++. A pointer stores the address of another variable. Pointer operators like & and * are explained. Declaring and accessing pointers as well as pointer arithmetic are also covered.

Uploaded by

seadamoh80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Pointer

• A pointer is a variable which stores the address of another variable.


The only difference between pointer variable and regular variable is
the data they hold.
• There are two pointer operators in C++:
– & the address of operator
– * the dereference operator
• Whenever you see the & used with pointers, think of the words
“address of.”
• The & operator always produces the memory address of whatever
it precedes.
• The * operator, when used with pointers, either declares a pointer
or dereferences the pointer’s value.
• The dereference operator can be literally translated to "value
pointed by”.
• A pointer is simply the address of an object in
memory.
• Generally, objects can be accessed in two ways:
directly by their symbolic name, or indirectly
through a pointer.
• The act of getting to an object via a pointer to it,
is called dereferencing the pointer.
• Pointer variables are defined to point to objects
of a specific type so that when the pointer is
dereferenced, a typed object is obtained.
• At the moment in which we declare a variable this one
must be stored in a concrete location in this succession of
cells (the memory).
• We generally do not decide where the variable is to be
placed - fortunately that is something automatically done
by the compiler and the operating system on runtime, but
once the operating system has assigned an address there
are some cases in which we may be interested in knowing
where the variable is stored.
• This can be done by preceding the variable identifier by an
ampersand sign (&), which literally means, "address of”.
For example:
• ptr= &var;
• This would assign to variable ptr the address of
variable var , since when preceding the name of the
variable var with the ampersand ( & ) character we are
no longer talking about the content of the variable,
but about its address in memory.
• We are going to suppose that var has been placed
in the memory address 1776 and that we write the
following:
– var=25;
– x=var;
– ptr = &var;
• We have assigned to x the content of variable var
as we have done in many other occasions in
previous sections, but to ptr we have assigned
the address in memory where the operating
system stores the value of var , that we have
imagined that it was 1776 (it can be any address).
• The reason is that in the allocation of ptr we have
preceded var with an ampersand ( & ) character.
• The variable that stores the address of another
variable (like ptr in the previous example) is what
we call a pointer.
Declaring Pointers

• Declaring a pointer is reserving a memory


location for a pointer variable in the
heap.
• Syntax:
– type * pointer_name ;
• to declare a pointer variable called p_age, do
the following:
– int * p_age;
• Whenever the dereference operator, *,
appears in a variable declaration, the variable
being declared is always a pointer variable.
• Assigning values to pointers:
– p_age is an integer pointer. The type of a pointer is very
important. p_age can point only to integer values, never
to floating-point or other types.
• To assign p_age the address of a variable, do the following:
– int age = 26;
– int * p_age;
– p_age = &age;
– OR
– int age = 26;
– int * p_age = & age;
• Both ways are possible.
• Accessing the variables pointed to
– If you want to print the value of age, do the following:
• cout<<age;//prints the value of age
– Or by using pointers you can do it as follows
• cout<<*p_age;//dereferences p_age;
– The dereference operator produces a value that tells the pointer
where to point. Without the *, (i.e cout<<p_age), a cout
statement would print an address (the address of age). With the *,
the cout prints the value at that address.
– You can assign a different value to age with the following statement:
• age = 13; //assigns a new value to variable age
• *p_age = 13 //assigns 13 as a value to the memory p_age points at.
• N.B: the * appears before a pointer variable in only two places:
when you declare a pointer variable and when you dereference
a pointer variable (to find the data it points to).
• The following program is one you should study closely.
It shows more about pointers and the pointer
operators, & and *, than several pages of text could do.
void main()
{
int num = 123; // a regular integer variable
int *p_num; //declares an integer pointer
cout<< “num is ”<<num<<endl;
cout<< “the address of num is ”<<&num<<endl;
p_num = &num;// puts address of num in p_num;
cout<< “*p_num is ”<<*p_num<<endl; //prints value of
num
cout<< “p_num is ”<<p_num<<endl; //prints value of
P_num

}
Arrays and Pointers

• Arrays and pointers are intimately related in C++ and


may be used almost interchangeably. An array name
can be thought of as a constant pointer. Pointers can
be used to do any operation involving array
subscripting.
• Assume the following declarations:
– int b[5];
– int * bPtr ;
• Because the array name (without a subscript) is a
pointer to the first element of the array, we can set
bPtr to the address of the first element in array b
with the statement
– bPtr = b;
• This is equivalent to taking the address of the first element of the
array as follows:
– bPtr = &b[0];
• Array element b[3] can alternatively be referenced with the
pointer expression
• * ( bPtr + 3 )
• The 3 in the preceding expression is the offset to the pointer. When
the pointer points to the beginning of an array, the offset indicates
which element of the array should be referenced, and the offset value
is identical to the array subscript. The preceding notation is referred to
as pointer/offset notation. The parentheses are necessary, because
the precedence of * is higher than the precedence of +. Without the
parentheses, the above expression would add 3 to the value of the
expression *bPtr (i.e., 3 would be added to b [0], assuming that bPtr
points to the beginning of the array). Just as the array element can be
referenced with a pointer expression, the address
• &b[3]
• can be written with the pointer expression
• bPtr + 3
• The array name can be treated as a pointer and used in pointer
arithmetic. For example, the expression
• *(b+3)
• also refers to the array element b [ 3 ] . In general, all
subscripted array expressions can be written with a pointer and
an offset. In this case, pointer/offset notation was used with the
name of the array as a pointer. Note that the preceding
expression does not modify the array name in any way; b still
points to the first element in the array.
• Pointers can be subscripted exactly as arrays can. For example,
the expression
• bPtr [ 1 ]
• refers to the array element b[ 1 ] ; this expression uses
pointer/subscript notation. Remember that an array name is
essentially a constant pointer; it always points to the
beginning of the array. Thus, the expression
• b += 3
• is in valid, because it attempts to modify the value of the array
name with pointer arithmetic.
Structure
• The term structure in C++ means both a user-defined
type which is a grouping of variables as well as meaning
a variable based on a user-defined structure type.
• For the purpose of distinction we will refer to the user-
defined type side as structure definition and the
variable side as structure variable.
• A structure definition is a user-defined variable type
which is a grouping of one or more variables.
• The type itself has a name, just like ‘int’, ‘double’, or
‘char’ but it is defined by the user and follows the
normal rules of identifiers.
• Once the type has been defined through the C++ ‘struct’
keyword, you can create variables from it just like you
would any other type.
• Since a structure definition is a grouping of
several types: it is a group of one or more
variables.
• These are known as elements or member
variables as they are members of the
structure definition they are part of.
• For example a date would require a day, month, and
year.
– We can declare three separate variables like
• int day, month, year;
– This isn’t so bad, but what happens if you want to store
two dates and not one? You’d have to create three more
variables and give them unique names:
• int day1, month1, year1;
• int day2, month1, year2;
– This begins to become a hassle.
• But we can define structure that could be a ‘date’
which might be made up of three ‘int’ member
variables: ‘day’, ‘month’, and ‘year’.
• Before creating a structure variable you must
create a structure definition.
• This is a blue print for the compiler that is
used each time you create a structure variable
of this type.
• The structure definition is a listing of all
member variables with their types and names.
• When you create a structure variable based on a
structure definition, all of the member variables
names are retained.
• The only name you have to give is that of the
new structure variable.
• The element names within that variable will be
the same as in the structure type.
• If you create two structure variables from ‘date’,
both will have all three member variables with
the same name in both: ‘day’, ‘month’, and
‘year’.
struct Specification: Defining
Structures
• Syntax for defining structure

• The name of a structure definition is known as the


structure tag.
• This will be the name of the type that you create, like
‘int’ or ‘float’.
• It is the type that you will specify when creating a
structure variable.
• This structure block is similar to a statement
block since it starts and ends with curly braces.
– But don’t forget that it ultimately ends with a semi-
colon.
• Within the structure block you declare all the
member variables you want associated with that
type.
• Declare them as you would normal variables, but
do not try to initialize them.
• This is simply a data blue print, it is not logic or
instructions and the compiler does not execute it.
Example defining a student struct
• The following defines a structure called ‘date’ which
contains three ‘int’ member variables: ‘day’, ‘month’,
and ‘year’:

• Note: You cannot initialize member variables in a


structure definition. The following is wrong and will
not compile:
struct date{
int day = 24, month = 10, year = 2001;
};
• A structure definition has the same type of scoping as
a variable.
• If you define a structure in a function, you will only be
able to use it there.
• If you define it in a nested statement block, you will
only be able to use it inside there and any statement
blocks nested within it.
• But the most common place is defining it globally, as in
outside of any functions or blocks.
• Typically, you’ll want to be able to create variables of
the defined structure anywhere in your program, so
the definition will go at the top.
Declaring and using sturct data types
• Once you have defined a structure you can create a
variable from it just as you would any other variable.
– date birthday;
• The above declaration statements would create a
variable called ‘birthday’ whose type is the structure
‘date’.
• The variable contains three parts: ‘day’, ‘month’, and
‘year’.
• What this actually does is set aside a whole block of
memory that can contain all of the member variables.
• What this actually does is set aside a whole
block of memory that can contain all of the
member variables.
• Each member variable then occupies a chunk
of it for their individual storage units.
• The member variables are not actually created
one at a time.
• Storage for member variables exist at some
offset from the beginning of the glob of
memory reserved by the entire structure.
– For example, in our ‘date’ structure variable the
first member variable is ‘day’ so it exists at offset
0.
– The next member variable, ‘month’ in this case,
will exist at the next available offset. If ‘day’ uses
4 bytes (32 bits), then ‘month’ will be at offset 4:
Initializing Structure Variables
• You cannot initialize member variables in the
structure definition. This is because that
definition is only a map, or plan, of what a
variable based on this type will be made of.
• You can, however, initialize the member
variables of a structure variable.
• That is, when you create a variable based on
your structure definition you can pass each
member variable an initializer.
• To initialize a structure variable’s members,
you follow the original declaration with the
assignment operator (=).
• Next you define an initialization block which is
a list of initializers separated by commas and
enclosed in curly braces.
• Lastly, you end it with a semi-colon.
• These values are assigned to member
variables in the order that they occur.
• This creates a variable called ‘nco_birthday’
and initializes it to a list of values.
• The values are assigned to the member
variables in the order they are declared in the
structure definition.
• It is possible to use any expression that you normally
would. But remember that the expression must
result in a value.
• Here is an example of initialization with things other
than literals:
int myday = 19;
int mymonth = 5;
date nco_birthday = { myday, mymonth + 3, 2001 -
22
};
• Although you can assign a value to a variable in the
same way you initialize it, the same is not true with
structures. So while this works:
int x;
x = 0;
• This doesn’t:
date nco_birthday;
nco_birthday = { 19,
Accessing members of a structure
variable
• You can use a member variable in any place you’d use
a normal variable, but you must specify it by the
structure variable’s name as well as the member
variable’s name using the member operator.
• To specify that you want a member of a specific
structure variable, you use the structure member
operator which is the period (also known as a “dot”).
• Simply use the structure’s name, follow with the
period, and end with the member:
– structure.member
• Example: to reading and displaying values
to and from structure s1.
cin>>s1.id; //storing to id item of s1
cin>>s1.name; //storing a name to s1
cout<<s1.id; //displaying the content of
id of s1.
cout<<s1.name; //displaying name of s1
Example:-a program that creates student
struct and uses it to store student information.
Variables with Definition
• The syntax of ‘struct’ also allows you to create
variables based on a structure definition without using
two separate statements:
struct tag
{
member(s);
} variable;
• The structure variables created in this way will have
the same scope as their structure definition.
• This is a nice thing to use when you want to group
some variables in one place in your program without it
affecting other things.
Example: A ‘point’ variable right after the ‘pointtag’
structure is defined:
struct pointtag{
int x, y;
} point;
• In this, ‘point’ is a variable just as if we had
declared it separately. In fact, this statement
is identical to: struct pointtag{
int x, y;
};
pointtag point;
• Rather than defining a structure under a name
and then creating variables which refer to the
named definition, the definition becomes part
of the variable declaration.
• It is even possible to omit the structure tag
which may make more sense in this situation:
struct{
int x, y;
} point;
• The above creates a structure variable called
‘point’ which has two member variables.
Because the structure definition is not
named, it cannot be used elsewhere to create
variables of the same structure type.
However, like in any variable declaration, you
can create multiple variables of the same type
by separating them with commas:
struct{
int x, y;
} point1, point2;
• Or you can even initialize it.
struct{
int x, y;
} point1 = { 0, 0}, point2 =
{0, 0};
Array of structures
• An array of structures refers to an array in
which each element is of structure type.
• To declare an array of structures, firstly, a
structure is defined and then an array of that
structure is declared. The syntax for declaring
an array of structures is:
• Memory map of the above struct declaration.
0 id 1
name Tameru
1 id 2
name Hassen
2 id 3
name Selamawit
3 id 4
name Asia
4 id 5
name Micheal

You might also like