C Tutorial – Pointers

Pointers vs Arrays : are the same?

In this post we will take a look at the difference between Pointers and Arrays.

Pointers and Arrays are not the same thing but there are a lot of common syntax that you can use

The biggest thing that they have in common is that both are sequence of memory address that you can access.

Let’s have a look at the array: you know that when you pass a variable by value to a function what happen is that the C Compiler makes a copy of the local variable in the stack and pass the copy to the function. Although both variables have the same value their memory address is different: in other words they are located in a different section of the memory.

Now when you pass one array as a value to a function the C compiler does not copy the whole array in the stack: that would be very inefficient. The C compiler will copy only the address of the first element.

That is a bit similar to what happen with a pointer where the C compiler move through the memory blocks starting from the first bloc.

Let’s have a look at an example. We declare an array of for elements and we fill with some integer values.

int myarr[4];
myarr[0]=20;
myarr[1]=40;
myarr[2]=60;
myarr[3]=80;

Now let’s print the memory location of the array. There are several way of doing that. We can do this way

 printf("This is the memorry address of array using myarr     %p\n",myarr);

Notice please: We have an integer array but we are asking to print the memory address with printf using the a format specifier p!:Format specifier p is used to “writes an implementation defined character sequence defining a pointer” (source https://www.programiz.com)

Now we can also print the memory address of the integer pointer using a different syntax

printf("This is the memorry address of array using &myarr    %p\n",&myarr);
    printf("This is the memorry address of array using &myarr[0] %p\n",&myarr[0]);
    printf("This is the memorry address of array using &myarr[1] %p\n",&myarr[1]);
    printf("This is the memorry address of array using &myarr[2] %p\n",&myarr[2]);
    printf("This is the memorry address of array using &myarr[3] %p\n",&myarr[3]);

This will return the following values. Notice please: that if we do not pass the element of the array the Compiler (first printf statement) will return the address of the first element (this is similar to what happen with a pointer)

Now let’s suppose we want to have a pointer to the array

 int *pointerArray;
 pointerArray=myarr;

Let’s print the memory address of the pointer at different location

printf("\n");
    printf("------How to move between memory address of the pointerArray---------:\n");
    printf("This is the memorry address of the pointerArray base      %p\n",pointerArray);
    printf("This is the memorry address of the pointerArray+1         %p\n",pointerArray+1);
    printf("This is the memorry address of the pointerArray+2         %p\n",pointerArray+2);
    printf("This is the memorry address of the pointerArray+3         %p\n",pointerArray+3);

Those instruction will print all the memory blocs of the array

If I want to know the value of first element of array I can de-reference with the following standard command to de-reference the pointer

printf("This is the memorry address of the *(pointerArray+1)      %d\n", *(pointerArray+1) );

But I can also use (notice please) the array’s way to de-reference the pointer

printf("This is the memorry address of the pointerArray[1]        %d\n",pointerArray[1]);

The result will be exactly equal, in this example 40.

Once I have a pointer we can say that pointer is equal to an array. This expression is valid. However we cannot say that array is equal to pointer.

Here is the code of the example above

A Javascript Game

Let’s review now the Javascript code behind this small game.

First of all our little program define 4 elements:

One array called myarr

myarr={
    "it-flag.gif":"Italy",
    "tn_fi-flag.gif":"Finland",
    "tn_mx-flag.gif":"Mexico",
    "po-flag.gif":"Portugal",
    "ja-flag.gif":"Japan",
    "tn_us-flag.gif":"USA",
    "tn_ro-flag.gif":"Romania",
    "pl-flag.gif":"Poland",
    "tn_gm-flag.gif":"Germany"
};

This array contain all the flags that are loaded in the game.

We also define 3 elements more that will be accessible from any function of the program

randomNmber=0;
completedList=false;
var score=0;

Now the first function that we review is called startGame()

function startGame() {
    getNextEntry();
    document.getElementById("sourceimg").src=defineCandidate(randomNmber);

    if (completedList==true) {
        document.getElementById("sourceimg").src="win.gif";

    }
}

The first line of the function call the function getNextEntry. This is a function that define a random number. The function is below

function getNextEntry(){
    const val = Object.keys(myarr);
    max = val.length;

    if (max==0) {
        listTerminated()
        completedList=true;
    }

    else {
        randomNmber=Math.floor(Math.random()*max ) + 0;
    }

This function first get all the keys from the array myarr.

If we print to console the val object we will see that the array is a collection of all the flags loaded.

Array(9) [ “it-flag.gif”, “tn_fi-flag.gif”, “tn_mx-flag.gif”, “po-flag.gif”, “ja-flag.gif”, “tn_us-flag.gif”, “tn_ro-flag.gif”, “pl-flag.gif”, “tn_gm-flag.gif” ]

The variable max get the current lenght of the array

If the array is equal to zero than the user has won: in this case the program will call a listTerminated function that will print out the congratulation message for the player.

If the array is greater than zero then a random number is generated. The global variable (randomNmber) will be assigned a random number

Let’s go back to the function startGame.

In the html page we have a an image tag has the one below

Image Tag

Now we need to insert the randomly chosen flag in the image tag.

To do so we call the function defineCandidate(randomNmber) and we pass the random number as a parameter.

Let’s have a loo at the defineCandidate function.

//Return first Key of the Object
function defineCandidate(num){
    const keys= Object.keys(myarr);
    return keys[num];
}

If we console out the keys[num] the result will be :

Passing from number to file name.

As you can see anytime we press Start Game the function defineCandidate will receive a number as parameter and return the key (which in this case consist in the name file of the picture).

So far we have seen how to choose randomly a number from the Flag Array (myarr) and then pass the number to a function that will give us the name of the picture to insert in the img tag.

Let’s check now what happens when the user actual select the answer from the list of values and hit the confirm button.

As usual first the function and then the explanation

function okconf(){
    var userSelection=document.getElementById("Country")
    var countrySelected=userSelection.options[userSelection.selectedIndex].value;
    let flag_posted= myarr[defineCandidate(randomNmber)];

    if (flag_posted==countrySelected) {
        addscore();
    }

    else {
        removescore()
    }

    updateLOV(defineCandidateValues(randomNmber));
    removefromselection(flag_posted);
    startGame();
    
}

When the user hit the button “Confirm” the function okconf() is called.

First of all a variable userSelection is generated: this variable is populated with the drop down list of value. Let’s have a look at what happen when we press confirm and console out the userSelection variable.

userSelection variable returns the drop down menu

At this point we need to get the value actually displayed in the drop down (in the picture above we need to get Finland).

To do so:

countrySelected=userSelection.options[userSelection.selectedIndex].value;
We use the selectedIndex command from the drop down menu to get the value of the country chosen by the user.

At this point we know that the user has selected one country (for example Finland).

We need to check if the answer from the user is equal to the flag displayed.

We still have our randomNumber referring to the array. So all we need to do is get the value from the array dictionary

Once this is done we can check if the answer provided by the user is correct or not. If it is correct we will call addscore, otherwise removescore

The functions addscore and removescore are self-explanatory.

Let’s instead keep going with our function okconf.

After updating the score the function call the function updateLOV. This function receive as a parameter the name of the country displayed.

//Remove item from list of values in the webpage
function updateLOV(mycountry){
    mylist=document.getElementById("Country");
    console.log(mylist);
    for (i=0;i<mylist.length;i++) {
        if (mylist[i].value==mycountry) {
            mylist.remove(i);
        }
    }
}


The function above assign to mylist the selection list of values. So mylist is a type array with all the values

Then the function start a loop inside the array mylist and check if the value of the list is equal to the name of the country received as a parameter. If that is the case from mylist the value of the country is removed.

So far we have removed from the list of value the name of the country displayed. We need also remove the country selected from the global array

We do so with the function below

//delete the item from the object 
function removefromselection(flag_posted) {
    item_to_remove=defineCandidate(randomNmber);
    delete myarr[item_to_remove];
    //console.log(myarr);       
}

Pie Charts

In this section we will be looking at Pie charts. Let’s see a small example. Suppose that we want to chart the distribution of active hours for a standard day.

Let’s suppose that 70% of the active hours are taken by work and than the rest of the day is equally split between Programming, Reading and Sport (that is how much I can at the moment).

Let’s have a look at the code below:

import matplotlib.pyplot as plt
l=["Work","Sport","Programming","Reading"]
mytime =[70,10,10,10]
e=(0,0,0.2,0)
fig1,ax1=plt.subplots()
ax1.pie(mytime, explode=e,labels=l,autopct="%1.1f%%",shadow=True,startangle=90)
ax1.axis('equal')
plt.title("Day Distribution")
plt.show()

We have a variable for the Label (l) and a variable with the hours distribution.

The variable “e” is used to indicate MatPlot which slice of the Pie we want to detach from the Pie (in this case we are selecting the Programming element (the third in the list)

The other important part of this small program is the ax1.pie where we insert the :

  • values to plot (mytime variable)
  • we set the explode flag so that we can detach the 3rd element of our list
  • the label (variable l)
  • the format of the data (autopct)
  • shadow paremeter is set to True
  • startangle set to 90

Here is our Pie Chart