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

Leave a Reply

Your email address will not be published. Required fields are marked *