PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] What is wrong in passing pointer variable as an function argument instead of address of variable in C?

 July 05, 2022     c, function-declaration, pass-by-reference, pass-by-value, pointers     No comments   

Issue

I know that if I pass &a as an argument in fun ,I will get result as *p =20 after fun is executed .Now see in the following code p is pointer variable passed as an argument to function fun. But after compilation I get result as *p =10 instead of 20 .

What is wrong in passing pointer variable p instead of address of a i.e. &a to function fun?

#include <stdio.h>
int a = 10, b = 20;
void fun(int *p)
{
    p = &b;
}
int main()
{
    int *p = &a;
    fun(p);
   //fun(&a);

    printf("%d\n", *p);
    return 0;
}

Solution

The function parameter p

void fun(int *p)
{
    p = &b;
}

is a local variable of the function. The function deals with a copy of the value of the pointer passed to the function

fun(p);

So within the function it is its local variable that is changed.

You may imagine the function and its call the following way (I will rename the function parameter to ptr for clarity)

fun(p);

//...

void fun( /* int *ptr */ )
{
    int *ptr = p;
    ptr = &b;
}

As you can see the original pointer p was not changed.

If you want to change the pointer you need to pass it by reference. In this case the function will look like

void fun( int **p)
{
    *p = &b;
}

and in main it is called like

fun( &p );

In this case the pointer p (and not a copy of its value) will be indeed changed in the function.

That is the general rule is if you want to change an object in a function you nned to pass it to the function by reference. In C passing by reference means passing an object indirectly through a pointer to it. In this case dereferencing the pointer you will get a direct access to the original object.



Answered By - Vlad from Moscow
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing