C Tutorial – Pointers

C Array of Pointers

Array of Pointers are very useful in C, especially when you deal with Strings.

Let’s review a small example.

We start declaring a array of pointer as follow:

char *mylist[] = {
        "Java",
        "C",
        "Python",
        "Javascript",
        "Java"
    };

We also want to declare a variable type integer that we will use later.

int yourselection;

In our example we will give the user the option to select the programming language that is like the most.

 printf("What do you like programming\n");

    printf("0:Java\n");
    printf("1:C\n");
    printf("2:Python\n");
    printf("3:Javascript\n");

    printf("Please enter your selection:");

Now we ask the user to select one option:

printf("Please enter your selection:");
    scanf("%d",&yourselection);
    printf("%s\n",mylist[yourselection]);

In the code above we read the option provided by the user and then we print it out as shown in the figure below:

If you notice we call the array of pointer “mylist” and we pass the parameter that the user has selected.

Using array of pointers has also one benefit especially when dealing with strings: we can compare easily between 2 strings without need to check character by character the string nor we need to use the library function strcmp

Let’s view a practical application of that. Once the user selected is option the program will check if the user like C the most or not and print a different statement.

Here is the code:

 if (mylist[yourselection]==mylist[1]) {
        printf("You selected C, Congratulation\n");
    }

    else{
          printf("You have selected %s", mylist[yourselection] );  
          printf(" which is not my favorite\n");
        }

Here is what happen if we select Java for example

As you can see we were able to compare strings very easily without going character by character.

Here is the full program

C Tutorial – Pointers

C Dynamic Integer Array using Pointers

This is a small tutorial on how to create a Dynamic Integer Array in C using pointers.

Python and Javascript have their own to add an element to an array.

In C static array do not have the possibility to change the size of an array.

However if we use Pointers we can achieve the some functionality.

Let’s review an example together.

We start our example by declaring an integer pointer and allocating 20 blocks of memory. We do that using the malloc command.

 int *a=(int*)malloc(20 * sizeof(int));

We also want to declare a second variable type integer

int b;

At this point we can first fill the pointer with an integer value

  // Fill the pointer
    for (int i =0; i<20; i++) {
        a[i] = i+1;
    }

If we loop through this pointer we will can print all its value that will range from 1 to 20.

Now let’s suppose that the user wants to change the size of the pointer.

 //Ask the user an input
    printf("\n");
    printf("Please give me one number:");
    scanf("%d",&amp;b);
    printf("%d\n",b);
    

So we ask the user to give a number and we store the number in the variable integer b.

Now let’s resieze the pointer using realloc : so in fact we re-allocate memory to our pointer.

 //Reallocate memory of the pointer a
    a=realloc(a,b*sizeof(int));

Let’s fill the array too with the integer value as we did before

 //Fill the array
    for (int s =0; s<b; s++) {
        a[s] = s+1;
    }


    // Reprint the pointer
    for (int s =0; s<b;s++)   {
        printf("%d ", a[s]);
    } 

Let’s run the code to check how the program

Running the C Program

You can download the whole example here

C Programming

This section is dedicated to C Programming.

Some reason to learn C:

  1. The Kernel of Linux is written in C, so like any other Android Operating System (but also Windows..).
  2. C is the language used to write other programming language (for example Python).
  3. C is the best programming language to interact with hardware (drivers are normally written in C / C++)
  4. One more thing about C : it is a language that allows to manage the memory allocation. This give the developer the possibility to write very efficient and fast program compared to other Programming Language

We start this section with a small example of C manipulating string. We assume that you have some basic knowledge of C.

The first program of this C-series is about manipulation of String.

The objective is to write a small program that takes a coded message and decode it.

To decode it, the program will reverse the string, put everything in lower and strip any character that is not a letter.

For example: if the input is the following:

Sei%%23r!eS eh$T eg!a#ugnaL g!n”im$m&a&r&g9or/P// C

The output will be “C Programming Language The SerieS”

Lets review the important part of the program. The full program will be available in the link below.

The program will use 2 pointer functions type char. The first function will reverse the string.

The second will decode it

We will use the library string but also the stdlib (the latter used for the malloc function)

Note: replace (def op) with the & char in the below code.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *rev(char *p, int l);
char *decode(char *p, int l);
char *freem(char *p);

int main() {

	char *p; //Original input
	int l;	// Measure the string
	p=(char*)malloc(200*sizeof(char)); //allocate memory to the pointer
	printf("Please enter an input string:");
	fgets(p,200,stdin);
	l=strlen(p);
	p=rev(p,l);
	p=decode(p,l);
	printf("%s\n",p);
	freem(p); // Memory is freed

	return 0;

}

char *rev(char *p, int l) {

	int c=0;
	char *r;
	r=(char*)malloc(200*sizeof(char));
	for (int i=l-1;i>=0;i--) {
		strncat(r,(def op)p[i],1);
	}
	return r;
	freem(p);
}


char *decode(char *p, int l) {

	char *r;
	char x;
	char xint;

	r=(char*)malloc(200*sizeof(char));

	for (int i=1;i<l;i++) {
		if (p[i]==' ') {
			strncat(r,(def op)p[i],1);
		}

		else {
			xint=(int)p[i];
			if ((xint>=65) &amp;&amp; (xint<=90)) {
				x=(char)xint;
				strncat(r,(def op)p[i],1);
			}

			if ((xint>=97) &amp;&amp; (xint<=122)) {
				x=(char)xint;
				strncat(r,(def op)p[i],1);
			}
		}

	}

	return r;
	freem(r);
}



char *freem(char *p) {

	free(p);
	p=NULL;
	return p;

</pre>

Line 9-24 is the main block of the program.

In line 11 we declare a pointer and in line 13 we allocate memory using malloc.

Then we read the input from the user using fgets(line 15). In line 16 we measure how long is the string.

Then we call our first function to reverse the string.

char *rev(char *p, int l) {    
    int c=0;
    char *r;
    r=(char*)malloc(200*sizeof(char));
    for (int i=l-1;i>=0;i--) {
        strncat(r,&amp;p[i],1);
    }
    return r;
    freem(p);
}

This function take 2 inputs : one char pointer and an integer. The integer represents the length of the string.

The function has a variable pointer variable type char r. As done previously we allocated 200 bytes to the pointer to this variable(r).

To reverse the string is done with a loop until i>=0 : the loop will take the char &p[i] and concatenate it with a char pointer (r). The operation is done until i=0. In each iteration the variable l is reduced by one.

Once the char pointer is returned to the main program we call another function: the decode function.

The decode function (line 18) takes 2 inputs: a char pointer and an integer measuring the length of the string. A pointer is allocated memory like before (200 bytes). The a loop starts (line 47):

For each char of p[i] a check is done to verify if it is a space. If that is the case the space is contacted with the pointer .

To concatenate we use the function strncat (line 49). strncat is a function included in the string library.

If the condition above is not met (char is not a space) first we cast the char to an integer number using the expression

xint=(int)p[i];

Then we verify whether:

A) the corresponding integer number is between 65 and 09 (A-Z). In this case the character is added to string by concatenation.

B) the corresponding integer number is between 97 and 122 (a-z). Also in that case the character is added to the string by concatenation.

A char pointer (r) is returned to the main program.

Then we free the memory and set the pointer equal to NULL.

Here some examples

Example 1
Example 2