The interaction of pointers and arrays can be confusing but here are two fundamental statements about it:

  • A variable declared as an array of some type (e.g. int) acts as a pointer to that type. It points to the first element of the array.
  • A pointer can be used like an array name.

Example 1

This example describes some basic concepts of arrays and pointers. Every line commented with explanation. 

#include<iostream>
using namespace std; // syntax for using the namespace std from the header file, iostream

	void function1(int *); // declaring the ptototype

	int main()
	{
		int   intArray[] = {12, 31, 43, 56, 42 };
		int   *myPtr;   // An integer type pointer
		myPtr = intArray; // BECAUSE intArray = &intArray[0]

		function1(myPtr); // Function called

		getchar(); // press a key to exit
		return 0;
	}

	void function1(int *ptr)
	{
		cout<<"function1 has been called: "<<endl;

		cout<<"The original elements of the array are: "<<endl;

		for ( int  i = 0;  i < 5;  i++ )
			cout<< *(ptr++) << endl; // print the elements of the array one by one, using pointer

		ptr -= 5; // go back to the first element

		cout<<" The changed elements of the array are: "<<endl;

		for ( i = 0; i < 5; i++ )
		{
			*ptr += 100; // add 100 to each derefernced value
			cout<< *(ptr++) << endl; // go to next value, and print it
		}
	}

Pointers and Structures

Struct is used to declare a new data-type. Basically this means grouping different data type variables together. For example, a struct data type could be used to declare the format of the following file.

   
   Jo               Maths    A
   Harry Carpenter  English  A
   Billy King       Maths    C

The records above could be described in a struct as follows:

      struct
   {
       char cname[8];
       char sname[16];  
       char grade;
   } record;

The statement above declares a variable called record with 3 members called cname, sname, grade. The structure as a whole can be referred to as record and a member can be referenced as record.exam.

Structures can be declared in various forms…

     struct x {int a; int b; int c;};   /* declaration */
     x z;
     struct       {int a; int b; int c;} z;

All the examples above are structure declarations,

  • The first gives x as a ‘structure tag’.
  • The first and third declare the members of the structure.
  • Second and third give z this is the variable that assumes the structure type.

Structure membership

We can access individual members of a structure with the ‘.’ operator.

For example to assign a value, we can enter: 

#include<iostream>
    using namespace std;

   struct x {int a; int b; int c;};

   int main()
   {
      x z;
      z.a = 10;
      z.b = 20;
      z.c = 30;

      return 0;
   }

And to retrieve a value from a structure member:

#include<iostream>
    using namespace std;

struct x
   {
      int a;
      int b;
      int c;
   };

   int main()
   {
      x  z;

      z.a = 10;
      z.a++;

      cout<< "first member is: "<< z.a;
   }

Pointers to structures

All that we have discussed so far has been OK but runs into problems when structures have to be moved between functions for the following reasons.

  • If the structure is large it is more efficient to pass a pointer to the structure instead of the structure itself. This technique is also used to pass pointers to arrays between functions.
  • When passing a structure to a function, you actually pass a COPY of the structure. Therefore it is not possible to change the values of members within the structure as the copy is destroyed when the function ends.

So how does it all work? Here is an example.

#include<iostream>                | #include<iostream>
using namespace std;              | using namespace std;                   
struct x {int a; int b; int c;} ; | struct x {int a; int b; int c;} ;      
void function(x);                 | void function(x *);                    
int main()                        | int main()
{                                 | {
  x z;                            |   x z, *pz;              /* 3 */
                                  |   pz = &z;               /* 4 */
  z.a = 10;            /* 1 */    |   z.a = 10;
  z.a++;                          |   z.a++;
                                  |
  function(z);         /* 2 */    | function(pz);            /* 5 */
  return 0;                       |  return 0;
}                                 | }
                                  |
void function(x z)                | void function(x * pz)
{                                 | {                        /* 6 */
  cout<<"first member: "<< z.a;   |  cout<< "first member: "<< (*pz).a );
}                                 | }

Here is the annotation.

  1. Give a structure member a value.
  2. Pass a COPY of the whole structure to the function.
  3. Define ‘pz’ a pointer to a structure of type ‘x’.
  4. Put the address of ‘z’ into ‘pz’. ‘pz’ now POINTS to ‘z’. PLEASE NOTE. ‘z’ is defined to reserve memory equal to the size of the structure. ‘pz’ only holds an address so will be 4 bytes long.
  5. Pass the pointer into the function.
  6. Print the value of the member ‘a’.

The (*pz).a syntax is used a great deal in C and it was decided to create a short hand for it. So:

               (*pz).a   ==  pz->a

Acknowledgement

Most of the contents above have been taken directly from here solely for educational purposes.

Exercises

1- Write a program having a function int BinarySearch( int *, int searchKey, int low, int high ) which takes as arguments, 1- the address of an integer array(sorted), 2- the key to be searched, 3- the lowest index of the array and 4- the highest index of the array. When the function executes, it returns the index of the key in case the key to be searched exists in the array; and -1, otherwise. Use pointer notation throughout; the only place you need brackets ([ ]) is in defining the array.

2- Write a program having a structure named Time which has 4 integer data items; days, hour, minute and second. Your task is to add variables of Time data type through a function void AddTime(Time *time1, Time *time2) which takes as arguments the addresses of two Time type variables, adds these variables and stores the result in time2. Your function must satisfy the following:

  1. If second exceeds 60 then add 1 in minutes and subtract 60 from seconds.
  2. If minute exceeds 60 then add 1 in hours and subtract 60 from minutes.
  3. If hour exceeds 24 then add 1 in days and subtract 24 from hours.

Test this function and print the result in the calling function.


Tagged with: C/C++ languageProgrammingSource Code
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.