Pointers In c Programming – With Examples

Pointers in c programming with examples is a series of tutorial aimed at teaching the complete lessons concerning pointers in c programming language.

The series will cover from the basics of pointers to advance pointers in the following order

  1. Pointer Basics
  2. Pointer Arithmetic
  3. Void and Dangling Pointer
  4. Dynamic Memory Allocation
  5. Array and Pointer
  6. String and Pointer
  7. Structure Pointer
    • Pointer to structure and arrow operator
    • Passing structure pointer to function
    • Function returning structure pointer
  8. File Pointer
    • File Basics and Reading
    • File right
    • File copy
  9. Function Pointer
    • Pointer to Function
    • Passing and return function pointer from function
    • Function Pointer application

Pointer Basics

Computer memory address basics

Every memory location in a computer has an address and a pointer is used to store such addresses. So we can say that a pointer refers to or references a memory address.

As shown in the image above, the Pointer refers to or references the address of the string variable ‘a’. So using a Pointer, we can access the data stored in a computer memory location.

Computer memory is linear in nature. The memory is organized in a contiguous manner. Each block in the computer memory represents 1 byte.

Each block has a unique address, see image below

Please note that for quick apprehension i have represented computer memory addresses here in decimal number whereas computer memory addresses are hexadecimal numbers.

One block of memory is a byte and 1 bytes contains 8 bits. Each bit can either be zero or

one. The entire computer memory is made up of zeros or ones.

Each datatype requires a specific amount of memory.

  • Char datatype which stores characters requires 1 byte (8bits)
  • Int datatype which stores whole numbers excluding decimals requires 4 contiguous bytes (32bits)
  • Float datatype stores numbers that can have a fractional part and requires 4 contiguous bytes (32bits)
  • Double requires 8 contiguous byte of memory (64 bits)

You can go here http://web.engr.oregonstate.edu/~rookert/cs162/ecampus-video/CS161/template/chapter_2/datatypes.html to learn more about datatypes.

So in summary to store

  • A char value, the computer allocates 8 bits
  • An int or a float value, the computer allocates 32 bits
  • A decimal value, the computer allocates 64 bits

To confirm that a computer memory allocates hexadecimal numbers, run the following code to see the output of &i

#include<stdio.h>

int main()
{
    int i = 10;
    //Write your statement here;
    printf("%d ", &i);
    
    return 0;
}

Variable address

You get the address of a variable by using Ampersand sign before the variable name for instance &i where i is the variable name.

Consider this code

int i = 10;
printf("%d ", &i);
printf("%d ", &i + 1);

First we have integer variable i which is assigned the value 10 and we have learned that an integer datatype takes up 4bytes of computer memory; therefore 4 bytes will be allocated by the computer to variable i. Let us assume that the address allocated is from 1024 to 1027 as seen in the following image

The starting address which is also known as the base address is 1024.

The second statement in the code prints the address of variable i which is 1024 (what it prints is the base address of the memory block).

The last statement in the code is asked to print &i + 1, can you guess what the answer will be. If you say 1025, you are wrong; remember that an int takes up 4 bytes of memory, therefore the right answer will be to add 4 to the base address of variable i which is 1024 + 4 = 1028. The block of memory will look like the image below

What if the line of code was this instead,

printf("%d ", &i + 5);

then the answer will be 1024 + (5 * 4) = 1044

What if variable i was of datatype char instead of int,

&i + 1;

will rather be 1024 + 1 = 1025 since char takes up only 1 byte of computer memory, and

&i + 5;

would have been 1024 + (5 * 1) = 1029

So in summary we can say that

Variable Address + N = Base Address + (N * sizeof(datatype))

Uses of pointers

Memory Management

Pointers save memory space and improve efficiency. Consider the following code

struct employee{
    char name[4];
    int age;
    float weight;
}
void fun(struct employee);

int main(){
    struct employee e = {"eva", 40, 40.09};
    fun(e);

    return 0;
}

void fun(struct employee obj){

}

The struct employee will occupy 4 byte for name (4 byte because its an array of 4 elements), 4 byte for age and 4 byte for weight making a total of 12 bytes of data.

Now you can see from the code that in the main function we make a function call to the function fun passing in an object of struct employee e as parameter. This will copy all the values to the function, meaning the parameter e will occupy another 12bytes of computer memory inside the called function fun(). This is not a good approach because of duplication of memory.

Now to manage memory, see the following code

struct employee{
    char name[4];
    int age;
    float weight;
}
void fun(struct employee);

int main(){
    struct employee e = {"eva", 40, 40.09};
    fun(&e);

    return 0;
}

void fun(struct employee *obj){

}

same scenario as the previous code apart from that this time we pass a pointer pointing to the memory address of the struct employee e. This way only the starting or base memory address is passed to the function and that is how pointer saves memory space and improves efficiency.

Dynamic Memory Allocation

Using pointers, we can create, resize and delete memory based on our needs at run time

The syntax to declare a Pointer variable is

datatype *Pointer_name;

where * indicate that the variable is a pointer type. Datatype in the syntax above can be int, char, float etc.

In the part two of this series on Pointers in c programming, we will handle Single Pointers, Pointer to Pointer, call by value versus call by reference and Function returning pointer.

To learn more about Pointers in c programming and to gain enough practice time from interview questions including hints when you don’t know how to move forward with the challenge, i recommend log2base2. The have a course called Problem Solving With DSA and one of the courses under Problem Solving With DSA is Pointers in c. It is a complete syllabus on the subject. See some of the Pointers practice problem syllabus in the image below

As a beginner to advanced computer programming courses like Data Structure and Algorithms, Advance Pointers, dynamic programming etc., log2base2 is the easiest place to get started. And they’ve provided and environment in each class where you can compile your practice problem code and get outputs on screen right there.

The have a free 3 days trial which you can use to test the waters to see if the course is good for you. Click here https://log2base2.com?refID=3Q89F0UF1KUWNQZ to go check them out.

For Pointers in c programming part 2, click here https://firstclicklimited.com/tutorials/index.php/2021/02/04/single-pointers-pointer-to-pointer-call-by-value-vs-call-by-reference-function-returning-pointer-in-c-programming/

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like