C Pointers and Arrays

C Pointers and Arrays: Practical Guide (with Examples)

Do you like puzzles? If so, then working with C pointers and arrays in programming might just be your cup of tea. These powerful tools offer endless opportunities for creative problem-solving and tinkering, allowing you to optimize your code and create truly unique solutions.

What are Pointers and How to Use Them

Pointers are one of the most important concepts in C programming. A pointer is a variable that holds the memory address of another variable. Think of it like a signpost that tells you where to find something.

Imagine you have a box of cookies 🍪, and you want to share some with your friend. You tell your friend the location of the box, which is in the kitchen. Your friend uses that information to find the box of cookies and take some.

In C programming, a pointer works the same way. You use a pointer variable to store the memory address of another variable. Then you can use the pointer to access the value of that variable or modify it.

Here is an example:

int cookies = 10;  // create a variable called cookies and set its value to 10
int *ptr = &cookies;  // create a pointer variable called ptr that points to the address of cookies
// use the pointer to access the value of cookies and print it
printf("There are %d cookies\n", *ptr);
// use the pointer to modify the value of cookies
*ptr = 5;
// print the new value of cookies
printf("Now there are %d cookies\n", cookies);

In this example, we create a variable called cookies and set its value to 10. Then we create a pointer variable called ptr and use the “&” operator to get the address of the cookies variable.

We can then use the pointer to access the value of cookies and print it.

Output:

The are 10 cookies
Now there are 5 cookies

What are Arrays and How to Use Them

Arrays are another important concept in C programming. An array is a collection of elements of the same data type that are stored in contiguous memory locations. It is like having a group of things that are all the same and stored in a row.

Imagine you are at a party and there is a table with a bunch of cupcakes on it. Each cupcake is the same flavor, and they are all arranged in a row.

You can easily access each cupcake by counting how many cupcakes away it is from the first one.

In C programming, an array works the same way. You use an array to store a collection of elements of the same data type in contiguous memory locations.

Here is an example:

int cupcakes[6];  // create an array called cupcakes that can hold 6 integers
// assign values to the array elements
cupcakes[0] = 5;
cupcakes[1] = 3;
cupcakes[2] = 2;
cupcakes[3] = 8;
cupcakes[4] = 1;
cupcakes[5] = 6;
// print the values of the array elements
printf("There are %d cupcakes\n", cupcakes[0]);
printf("There are %d cupcakes\n", cupcakes[1]);
printf("There are %d cupcakes\n", cupcakes[2]);
printf("There are %d cupcakes\n", cupcakes[3]);
printf("There are %d cupcakes\n", cupcakes[4]);
printf("There are %d cupcakes\n", cupcakes[5]);

In this example, we create an array called cupcakes that can hold 6 integers. We then assign values to the array elements using square brackets and index numbers. We can then use the array to access each element and print its values.

In C, you declare an array by specifying the type of data it will hold, followed by its name and the number of elements it will contain.

For example, let’s say you want to create an array of 5 integers:

int myArray[5];

This declares an array called myArray that can hold 5 integers. You can access each element of the array by using its index, which is a number that represents its position in the array.

In C, array indexes start at 0, so the first element of myArray would be myArray[0], the second would be myArray[1], and so on up to myArray[4].

There are also different ways to initialize an array in C. You can assign values to each element of the array when you declare it, like this:

int myArray[5] = {1, 2, 3, 4, 5};

This sets the first element of myArray to 1, the second to 2, and so on.

If you don’t assign values to all the elements of the array, the remaining ones will be set to 0.

You can also leave out the size of the array when you declare it, and let the compiler figure it out based on the values you assign:

int myArray[] = {1, 2, 3, 4, 5}

This will create an array with 5 elements, just like the first example.

What are the differences between pointers and arrays

While pointers and arrays are related concepts in C programming, there are some important differences between them.

  • An array is a collection of elements of the same data type that are stored in contiguous memory locations. A pointer is a variable that holds the memory address of another variable.
  • An array has a fixed size that is determined when it is declared. A pointer can point to any variable of the same data type, regardless of its size or location in memory.
  • An array variable is itself a constant pointer to the first element of the array. For example, if you have an array called “myArray”, then the variable name “myArray” is a constant pointer to the first element of the array. You cannot change the memory location it points to. A pointer variable can be changed to point to different memory locations during program execution.
  • You can use array subscript notation to access individual elements of an array. For example, to access the second element of an array called “myArray”, you would use the notation “myArray[1]”. When using a pointer, you must dereference the pointer to access the value it points to. For example, if you have a pointer called “ptr” that points to an integer variable, you would use the notation *ptr to access the value of that variable.

Here is an example that demonstrates some of these differences:

int myArray[5] = {1, 2, 3, 4, 5};  // create an array of 5 integers
int *ptr = myArray;  // create a pointer to the first element of the array
printf("%d\n", myArray[2]);  // prints the value of the third element of the array (3)
printf("%d\n", *(ptr + 2));  // also prints the value of the third element of the array (3)
myArray = ptr;  // illegal! You cannot change the location myArray points to
ptr = &myArray[2];  // legal! You can change the location ptr points to

In this example, we create an array of 5 integers called “myArray” and a pointer to the first element of the array called “ptr”.

We can access the value of the third element of the array using both array subscript notation and pointer arithmetic.

We then demonstrate that you cannot change the location that an array points to, but you can change the location that a pointer points to

C Pointers and Arrays Examples

Prerequisites

A basic but well-rounded understanding of C programming. You can acquire these by checking out the following posts:

Write a program that declares an integer variable and a pointer to that variable.

Set the variable’s value to 42, then use the pointer to change its value to 99. Finally, print out the variable’s value to make sure it has been changed.

Solution:

#include <stdio.h>

int main() {
    int myVar = 42;
    int *myPointer = &myVar;  // declare a pointer and point it to myVar
    printf("myVar = %d\n", myVar);  // print the variable's initial value
    *myPointer = 99;  // use the pointer to change myVar's value
    printf("myVar = %d\n", myVar);  // print the variable's new value
    return 0;
}

Output:

myVar = 42
myVar = 99

The program first declares an integer variable called “myVar” and sets its value to 42. It then declares a pointer variable called “myPointer” that points to the memory address of myVar using the & operator.

Next, the program uses the printf() function to print out the initial value of myVar. It then uses the * operator to dereference the pointer and set the value of myVar to 99.

Finally, the program uses the printf() function again to print out the new value of myVar.

So, in summary, the program declares an integer variable, declares a pointer variable that points to the memory address of the integer variable, prints the initial value of the integer variable, changes the value of the integer variable through the pointer, and prints the new value of the integer variable.

Write a function that swaps the values of two integers.

  • Prototype: void swap_int(int *a, int *b);

Solution:

#include <stdio.h>

void swap_int(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 42;
    int y = 99;
    printf("Before swap: x = %d, y = %d\n", x, y);
    swap_int(&x, &y);
    printf("After swap: x = %d, y = %d\n", x, y);
    return 0;
}

Output:

Before swap: x = 42, y = 99
After swap: x = 99, y = 42

The swap_int function takes two integer pointers a and b as arguments. Inside the function, we use pointer dereferencing (*a and *b) to access the values of the integers that the pointers point to.

We then declare a temporary integer variable temp, assigning it the value of *a, assigning the value of *b to *a, and then assigning the value of temp to *b.

In the main function, we declare two integer variables x and y, and set their values to 42 and 99, respectively.

We then use the printf function to print out the initial values of x and y, call the swap_int function to swap their values, and then print out the new values of x and y to confirm that the swap was successful.

Write a function that returns the length of a string.

  • Prototype: int _strlen(char *s);

Solution:

#include <stdio.h>

int _strlen(char *s);

int main() {
  char str[] = "Hello, world!";
  int len = _strlen(str);
  printf("Length of string is: %d", len);
  return 0;
}

int _strlen(char *s) {
  int length = 0;
  while (*s != '\0') {
    length++;
    s++;
  }
  return length;
}

Output:

Length of string is: 13

In this program, we declare a function called _strlen that takes a pointer to a character array (char *s) as its parameter and returns an integer.

The function iterates through each character in the array, incrementing a length variable until it encounters the null character ‘\0’, which marks the end of the string.

In the main function, we declare a string called str and initialize it to “Hello, world!”.

We then call the _strlen function, passing it the “str array“, and storing the result in an integer variable called “len“. Finally, we print out the value of “len“, which is the length of the string.

I hope this helps you understand how to calculate the length of a string in C! If you have any questions, feel free to ask in our FORUM – Rocodeify.

Write a function that reverses the content of an array of integers.

  • Prototype: void reverse_array(int *a, int n);
  • Where n is the number of elements of the array

Solution:

#include <stdio.h>

void reverse_array(int *a, int n) {
    int temp;
    for (int i = 0; i < n/2; i++) {
        temp = a[i];
        a[i] = a[n-i-1];
        a[n-i-1] = temp;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("Original array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    reverse_array(arr, n);
    
    printf("Reversed array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

In this implementation, the reverse_array function takes an array of integers a and its length n as arguments.

It then uses a for loop to iterate over the first half of the array, swapping the i-th element with the (n-i-1)-th element to reverse the order of the elements. The function modifies the array in place, so there is no need to return a value.

The main function demonstrates how to use the reverse_array function by initializing an array of integers, printing its original contents, calling the function to reverse its contents, and then printing the reversed contents.

Showing example with real numbers:

Let’s say we have an array of 10 integers {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.

To reverse the order of the elements in this array, we only need to iterate up to n/2, where n is the number of elements in the array. In this case, n is 10, so n/2 is 5.

During the first iteration of the for loop, we swap the first element (a[0]) with the last element (a[9]), yielding the array {10, 2, 3, 4, 5, 6, 7, 8, 9, 1}.

During the second iteration of the loop, we swap the second element (a[1]) with the second-to-last element (a[8]), yielding the array {10, 9, 3, 4, 5, 6, 7, 8, 2, 1}.

During the third iteration of the loop, we swap the third element (a[2]) with the third-to-last element (a[7]), yielding the array {10, 9, 8, 4, 5, 6, 7, 3, 2, 1}.

During the fourth iteration of the loop, we swap the fourth element (a[3]) with the fourth-to-last element (a[6]), yielding the array {10, 9, 8, 7, 5, 6, 4, 3, 2, 1}.

And finally, during the fifth and final iteration of the loop, we swap the fifth element (a[4]) with the fifth-to-last element (a[5]), yielding the array {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}.

As you can see, we only needed to iterate up to n/2 (5 in this case) to reverse the order of the elements in the array.

Write a function that prints n elements of an array of integers, followed by a new line.

  • Prototype: void print_array(int *a, int n);
  • Where n is the number of elements of the array to be printed
  • Numbers must be separated by a comma, followed by a space
  • The numbers should be displayed in the same order as they are stored in the array

Solution:

#include <stdio.h>

void print_array(int *a, int n) {
    for (int i = 0; i < n; i++) {
        printf("%d", a[i]);
        if (i != n - 1) {
            printf(", ");
        }
    }
    printf("\n");
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(a) / sizeof(a[0]);
    print_array(arr, n);
    return 0;
}

Output:

1, 2, 3, 4, 5

The function print_array takes two arguments: a pointer to an integer array a and an integer n, which is the length of the array.

The function then iterates over the array using a for loop and prints out each element of the array using printf function.

After each element, a comma and a space are printed, except for the last element of the array.

Finally, the function prints a newline character.

In the main function, an integer array arr is declared and initialized with values {1, 2, 3, 4, 5}.

The length of the array n is then calculated using the formula sizeof(a) / sizeof(a[0]), which divides the size of the whole array by the size of one element of the array, giving the number of elements in the array. The print_array function is then called with arr and n as arguments.

Conclusion

In conclusion, pointers and arrays are fundamental concepts in the C programming language.

Pointers provide a powerful way to manipulate memory and data structures, while arrays are useful for organizing and manipulating large amounts of data.

Understanding how to work with pointers and arrays is essential for writing efficient and effective C code.

By mastering these concepts, developers can write code that is more flexible, scalable, and easier to maintain.

Thank you for reading this practical guide on C pointers and arrays. We hope that you found it informative and useful.

If you have any comments or feedback, please feel free to leave them in the comment section below.

If you need any assistance with any of the tasks we covered, or have any other questions about C programming, we encourage you to post on our Forum, where our community of experienced developers can help you out.

Don’t hesitate to ask for help, we’re all here to learn and grow together!

Check out Codeacademy’s Learn C course at https://www.codecademy.com/learn/learn-c if you want to explore additional resources and learn more about C programming.


Posted

in

by

Comments

Leave a Reply

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