ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Advanced C Pointer Programming chapter 8: Pointers and functions

prodevelopertutorial August 3, 2020

Functions are building blocks of C programming language. In this chapter we shall see different ways to pass pointers to a function.

We shall concentrate on 2 aspects.

1. Sending pointers to a function
2. Returning pointers from a function.

Passing variable by pointer

This type of passing is also called as pass by value.
The use of passing by pointer is to change the data hold by the variable.

Simple example is a swapping example:

Example 1:

In the below example, we have a swap function that accepts 2 int pointer. And we get the data by deferring during the swap operation.

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

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

int main() 
{ 
    int a = 10;
    int b = 20;

    printf("before swap a = %d, b = %d\n", a, b);
    swap(&a, &b);
    printf("after swap a = %d, b = %d\n", a, b);

    return 0; 
} 

 

Output:

before swap a = 10, b = 20
after swap a = 20, b = 10

 

Passing a variable by value:

If you pass by value, then the copy of the arguments are stored in called function.

Hence even if we modify the values in the swap function, the same will not be reflected in the calling function.

Example:

In the same swap example, we are sending the variables in call by value.

Hence a copy of 2 variables will be there in swap function.

Hence any modification made on the arguments in the called function will not be reflected back to calling function.

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

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

int main() 
{ 
    int a = 10;
    int b = 20;

    printf("before swap a = %d, b = %d\n", a, b);
    swap(a, b);
    printf("after swap a = %d, b = %d\n", a, b);

    return 0; 
} 

Output:

before swap a = 10, b = 20
after swap a = 10, b = 20

 

How to pass strings to a function in C?

We can pass strings in the similar way that we pass normal integer variables by pointer as shown below:

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

void show(char *str)
{
    printf("The string is = %s \n", str);
}

int main() 
{ 
    char *str = "Hello World";

    char str_1[] = "www.ProDeveloperTutorial.com";

    show(str); // note that we dont need to send "&str"
    show(str_1);

    return 0; 
} 


Output:

The string is = Hello World
The string is = www.ProDeveloperTutorial.com

Returning a pointer from a function in C

To return a pointer, we need to declare the return type as the pointer to the appropriate data type.

In the below example, we allocate memory for an array and then return the address of that allocated memory.

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

int * allocate_memory(int len)
{
    int *arr = (int*) malloc(len * sizeof(int));
    for (int i = 0; i < len; ++i)
    {
        arr[i] = i;
    }

    return arr;
}

int main() 
{ 
    int *arr = allocate_memory(5);

    for (int i = 0; i < 5; ++i)
    {
        printf("%d\n",arr[i]);
    }

    return 0; 
} 

 

Output:

0
1
2
3
4

 

Returning a pointer to a local data from a function in C

Generally programmers tend to do this easy mistake, if they dont know how stack works.

If suppose you allocate memory statically and then try to return that address. The compiler will not give any warning.

But the address of the array returned is no longer valid once the function returns because the function’s stack frame is popped off the stack.

Even-though you will be able to print the value, it may be overwritten if another function is called.

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

int * allocate_memory(int len)
{
    int arr[len] ;
    for (int i = 0; i < len; ++i)
    {
        arr[i] = i;
    }

    return arr;
}

int main() 
{ 
    int *arr = allocate_memory(5);

    for (int i = 0; i < 5; ++i)
    {
        printf("%d\n",arr[i]);
    }

    return 0; 
} 

Output:

0
1
2
3
4

 

Passing pointer to a pointer (double pointer) to a function in C

From the above examples WKT,

1.If a variable is pass by value, then a copy of arguments will be passed to the function. Hence any modification for those variables inside the function will not be reflected in the called function.

2. If a variable is pass by reference, then any modification made in called function will be reflected in the calling function.

3. Now, if you want to modify any data pointed by the pointer then we need to send pointer to a pointer.

Example:

In the below example, we have a function called as allocate_memory, that will take pointer to pointer.

This is because we are allocating a memory (modifying) pointed by the pointer, then you need to pass a pointer to pointer to pointer.

if you want to modify a pointer in C, you need to pass a pointer to a pointer. If you need to modify a pointer to a pointer, you need to pass a pointer to a pointer to a pointer.

 

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

void allocate_memory(int **arr, int size) 

{ 
    *arr = (int*)malloc(size * sizeof(int));
    if(*arr != NULL) 
    {
       for(int i=0; i<size; i++) 
        { 
            *(*arr+i) = i;
        }   
    }
}

int main() 
{ 
    int *arr = NULL;
    allocate_memory(&arr, 5);

    for (int i = 0; i < 5; ++i)
    {
        printf("%d\n",arr[i]);
    }

    return 0; 
} 

 

Output:

0
1
2
3
4

 

 

 

 

 

Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT