Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I came across a question on pointer which is given below. I am not able to understand why the output of the code below is 1000 and not 10. Can anyone help me how it is possible?
#include<stdio.h>
int y;
void main()
{
int x, *px, **ppx;
x = 10;
y = 1000;
px = &x;
ppx = &px;
f3(ppx);
printf("%d", *px);
}
void f3(int **pp)
{
*pp = &y;
}
This statement:
px = &x;
assigns the address of x to px. This statement:
ppx = &px;
assigns the address of px to ppx. This statement:
f3(ppx);
passes the value of ppx to f3. In f3, this statement:
*pp = &y;
assigns the address of y to the place that pp points. pp is the parameter of f3, which was given the value ppx in the call.
That is, pp is ppx, which points to px. Since pp points to px, *pp = &y puts the address of y in px.
Now px points to y. Then this statement:
printf("%d", *px);
prints the thing that px points to, which is y, which is 1000.
This statement *pp = &y; causes to print 1000. Before calling f3() px points to address of x as px=&x; but in f3() px got modified as address of y.
int y;
void f3(int **pp){ /*since you didn't declare functin,
so either declare it or define before main() */
*pp = &y;/* px contains now address of y */
}
int main(){ /* use int main() instead of void main() */
int x,*px,**ppx;
x=10;
y=1000;
px=&x;/* px points to address of x*/
ppx=&px; /* ppx points to address of px */
f3(ppx); /* passing ppx i.e address of px
And in f3() *pp = &y means px got replaced by
address of y */
printf("%d",*px); /* prints value at address of y, not address of x */
return 0;
}
Compile your code always with -Wall flag, don't ignore warnings.
You can change an object in a function passing it by reference that is indirectly through a pointer.
For example
#include <stdio.h>
void f( int *p, int value )
{
*p = value;
}
int main(void)
{
int x = 10;
printf( "Before call f x = %d\n", x );
int *px = &x;
f( px, 20 );
printf( "After call f x = %d\n", x );
return 0;
}
The program output is
Before call f x = 10
After call f x = 20
In the program the function deals with a pointer to the variable x declared in main. That is the pointer points to the variable x. Dereferencing the pointer you get access to the variable and thus can change it.
*p = 20;
The same way you can change an object that has a pointer type. To do this you have to pass the object/pointer by reference as it was shown above.
For example
#include <stdio.h>
typedef int * T;
void f( T *pp, T p )
{
*pp = p;
}
int main(void)
{
int x = 10;
T px = NULL;
T *ppx = &px;
f( ppx, &x );
printf( "After call f *px = %d\n", *px );
return 0;
}
The program output is
After call f *px = 10
At the beginning of the program the pointer px that has the type int * (due to the typedef) is initialized by NULL. Then it is passed to the function f by reference
T *ppx = &px;
f( ppx, &x );
that is indirrectly through a pointer to the pointer px. Within the function the pointer px is reassigned with the address of the variable xby dereferencing the pointer pp that points to the original pointer px.
Related
Suppose that in the main function an int type varaible x has a value 20. IF the function is called 2 times as foo(&x) , whats the value of x?
#include<stdio.h>
void foo(int *n)
{
int *m;
m = (int *)malloc(sizeof(int));
*m = 10;
*m = (*m)*5;
n = m;
}
int main()
{
int x = 20;
foo(&x);
printf("%d",x);
}
Shouldn't the value of x be 50 since we are initializing the address of n with m which has the value 50 but its coming out to be 20?
The address of the n pointer is local to foo. So modifying the pointer inside foo has no effect outside of the function. But when dereferencing n, the pointed-to value can be changed.
For x to become 50, the last line of the foo function should have been:
*n = *m;
Can anyone explain me the difference among these two?
#include <stdio.h>
void main() {
int a = 10;
int *p = &a;
*p = 11;
}
and
#include <stdio.h>
void main() {
int a = 10;
a = 11;
}
For starters pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
The presented two programs actually are equivalent except that in the first program the variable a is changed through a pointer to it.
As it is written in the C Standard (6.2.5 Types, p.#20)
... A pointer type describes an object whose value provides a
reference to an entity of the referenced type.
This property of pointers is used in C to implement the mechanism of passing objects by reference to functions.
Consider the following program.
#include <stdio.h>
void f( int x )
{
x = 10;
}
void g( int *px )
{
*px = 10;
}
int main(void)
{
int x = 0;
printf( "Before calling f x = %d\n", x );
f( x );
printf( "After calling f x = %d\n", x );
x = 0;
printf( "\nBefore calling g x = %d\n", x );
g( &x );
printf( "After calling g x = %d\n", x );
return 0;
}
The program output is
Before calling f x = 0
After calling f x = 0
Before calling g x = 0
After calling g x = 10
As you can see after calling the function f the value of the variable x declared in main was not changed. The problem is that the function deals with a copy of the value of the variable x declared in main. That is the function parameter is a local variable of the function that was initialized by the value of the variable x declared in main. Changing the local variable does not influence on the variable x declared in main.
But when the variable x is passed to the function g by reference through a pointer to it then the function is able to change the original variable x declared in main by means of dereferencing the passed pointer.
Also bear in mind that when you allocate a memory dynamically then allocated objects do not have names. You only have pointers to dynamically allocated objects. For example
int *px = malloc( sizeof( int ) );
So to change the allocated object you also need to dereference the pointer
*px = 10;
In this case nothing, but suppose that you want to call a function, if want to edit the value of a FROM INSIDE that function, you'll need to use pointers.
#include <stdio.h>
void set_a(int *p, int val)
{
*p = val;
}
int main()
{
int a = 2;
printf("a is: %d\n", a); // a is 2
set_a(&a, 5);
printf("a is: %d\n", a); // a is 5
}
that's just one use case. for instance, when using heap allocations, you'll need to use pointers.
The two programs have the same observable effect.
What is the purpose of using pointer to change the value of mutable object?
One good use is to be able to reuse logic. Write it once and use it many times.
Example:
void foo(int *X, int *Y) {
/* some complex calculation */
*X = *X + *Y + 1;
*Y = *Y + *X + 2;
}
Now, you could use the function to do this "complex" calculation on different variables. You only need to write and test it properly once and can then reuse it many times.
int main() {
int a = 10, b = 20, c = 30, d = 40;
foo(&a, &b);
foo(&c, &d);
//...
}
Demo
Suppose I have a pointer
int *x;
Then I need to let the pointer point to an int of value, say 42.
Should I do this:
*x = 42;
or this:
int y = 42;
x = &y;
? What is the usual practice?
After this declaration
int *x;
the pointer x either is equal to NULL (if it is declared outside any function) or has an indeterminate value. So dereferencing the pointer like
*x = 42;
invokes undefined behavior.
You can write either
int y = 42;
x = &y;
or
x = malloc( sizeof( int ) );
*x = 42;
When you do:
int *x = 42;
you assigne the pointeur x to the memory case 42, that gonna make a segmentation fault.
The right way to do what you wan't is:
int y = 42;
x = &y;
x gets the adress of y (&y)
#include <stdio.h>
int main()
{
int y=42;
int x=&y;
printf("\nY = %d is at adress X = %d \n",y,x);
}
In the following code why doesn't the address of j gets overwritten in p when we call the foo function?
#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&i);
printf("%d ", *p);
}
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}
You are printing with foo - which sets p to 2, then you call a print to p, which is still set to 97 in that scope. foo does not set p globally.
Because p in main is another variable than p in the function. Consequently, even if p is changed inside the function, the value of p in main is still the same and still points to 97.
In more details:
int main()
{
int i = 97, *p = &i; // i is 97 and p points to i
foo(&i);
printf("%d ", *p); // This prints what p points to, i.e. 97
}
void foo(int *p)
{
int j = 2; // Here p still points to i in main
p = &j; // Now p points to j, i.e. the value 2
printf("%d ", *p); // So this prints 2
}
Just to repeat: The important thing is that p in main and p in foo are two different variables.
If you want the program to print 2 2 you can change the function to:
void foo(int *p)
{
int j = 2;
*p = j; // Change this line. This will change i in main
// and thereby also the value that p in main points to
printf("%d ", *p);
}
Below are the steps:
int main()
{
int i = 97;
int* p = &i; // 1. p points to i, i is 97.
foo(&i); // 2. Pass the address of i by value.
printf("%d ", *p); // 6. Print the value of i as neither p nor i have not changed inside foo().
}
// I've renamed the parameter name from p to q for clarity. q is local to
// foo() only; changes made to q are only visible within foo().
void foo(int* q)
{ // 3. q contains a copy of i's address.
int j = 2;
q = &j; // 4. q is set to the address of j.
printf("%d ", *q); // 5. Print the value of j.
}
If you would have done *q = 2 inside foo() you would have changed i's value to 2. That's because q contains the address of i.
The p in main is a different object in memory than the p in foo. Writing to one has no effect on the other. If you want foo to update the value of p in main, then you must pass a pointer to p:
#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&p);
printf("%d ", *p);
}
void foo(int **p)
{
int j = 2;
*p = &j;
printf("%d ", **p);
}
WARNING - doing this will invoke undefined behavior, since p will point to an object that no longer exists - once foo exits, j no longer exists, and p will be an invalid pointer. You may get the output you expect, or you may not.
In order for a function to write to a parameter, you must pass a pointer to that parameter:
void foo( T *ptr )
{
*ptr = new_value(); // updates the thing ptr points to
}
void bar( void )
{
T var; // var is an instance of T
foo( &var ); // have foo update the value of var
}
This is true for any non-array type T, including pointer types. If we replace T with the pointer type P *, we get
void foo( P * *ptr )
{
*ptr = new_value(); // updates the thing ptr points to
}
void bar( void )
{
P * var; // var is an instance of P *
foo( &var ); // have foo update the value of var
}
The semantics are exactly the same - the only thing that's changed is that var starts out as a pointer type.
Things get weird with array types, which we're not going to go into quite yet.
This question already has answers here:
Changing address contained by pointer using function
(5 answers)
Closed 4 years ago.
#include<stdio.h>
void foo(int*);
int main()
{
int i = 97, *p = &i;
foo(p);
printf("%d ", *p);
getch();
}
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}
Output is 2 97
Why not 2 2 ?
pointer p holds the address of j now so why 97 is printed ?
You can imagine the function call and its definition the following way. For clarity I'll rename the function parameter as q.
foo(p);
void foo( /*int *q*/ )
{
int *q = p;
int j = 2;
q = &j;
printf("%d ", *q);
}
As it is seen the function parameter (in this case q) is a local variable of the function that is initialized by the value of an argument (in this case by the value of the argument p)
So any changes of the local variable (q) do not influence on the original argument (p).
After exiting the function the local variable will not be alive.
If you want to change the argument itself you should pass it by reference. For example
void foo( int **p )
{
int j = 2;
*p = &j;
printf("%d ", **p);
}
However after exiting the function the original argument/variable p will be invalid because it stores the address of a non-alive local variable of the function j.
So an attempt to access the memory that was occupied by the function's local variable j results in undefined behavior of the program.
You could make the program correct by declaring the local variable j as having static storage duration. For example
void foo( int **p )
{
static int j = 2;
*p = &j;
printf("%d ", **p);
}
and call the function like
foo(&p);
In foo, you assign a new value to p. However this is a copy of the value of p in main, so the change is not visible in main.
If you dereferenced p, then it would change the value if i in main:
void foo(int *p)
{
*p = 2;
printf("%d ", *p);
}
p = &j;
just changes the value of the local variable p. This has no effect on the caller's p variable (because p was passed by value) or the variable that p previously pointed to (because you didn't indirect through it). If you want to change the caller's data, write:
*p = j;
Go through the above code line by line. Here I have written comments as control passes through each of the lines...
#include<stdio.h>
void foo(int*);
int main()
{
int i = 97, *p = &i; //Lets assume i has address 2000
foo(p); //p contains 2000 which is passed to foo. go to foo at 1.
printf("%d ", *p); // when control comes back no change to p it
//still points to 2000 which stores 97
getch();
}
void foo(int *p) 1: // in foo another local variable p is created.
//Let's call this lp. lp has now address 2000. i.e lp
//and p both point to i but one locally exists in a
// function and will be destroyed when control comes out
// of the function
{
int j = 2;
p = &j; // now local p i.e lp points to another var j
// address. Suppose lp has address 3000 now.
printf("%d ", *p); //val at address in lp is 2
}