Argha Ray
Argha Ray

Reputation: 15

C programming, use of pointers

I am unable to understand the following code in С, using pointers

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

int bags[5]={20,5,20,3,20};
int *next();

int main()
{
    int pos=5;
    *next()=pos;
    printf("%d,%d,%d",pos,*next(),bags[0]);
}

int *next()
{
    int i;
    for(i=0;i<5;i++)
    if(bags[i]==20)
        return(bags+i);
    printf("Error!");
}

Can anyone explain why the ans is 20,5,20.

Upvotes: 0

Views: 102

Answers (3)

yasouser
yasouser

Reputation: 5187

The output is 5,20,5.

Note: int *next(); ==> next() is a function that returns int*.

[1] The call to next() from the line *next() = pos;. C evaluates the function from left so next() gets called first. Because of if (bags[i] == 20), the function next() returns bags+i which is simply bags since i is 0 at the moment. So next() returned the address of bags which means *next() is nothing but the pointer to bags[0]. So bags[0] becomes 5.

[2] When the execution comes to this line: printf("%d,%d,%d",pos,*next(),bags[0]);, it prints value of pos i.e 5, value of *next() which is 20 as next() returned the address of bags[0].

[3] *next() prints 20 because, this time next will return the address of bags[2] since bags[0] got assigned with the value of pos in the line before the printf().

[4] And finally, bags[0] is 5. See the explanation in [1].

Upvotes: 0

Andrei Bozantan
Andrei Bozantan

Reputation: 3941

The function next returns a pointer to the first array element equal to 20. So, *next()=pos; will modify the first element of the array from 20 to 5. Then it is simple to understand why the output is 5,20,5: since pos is five, *next() returns 20 and bags[0] is 5 as explained above.

Upvotes: 0

LearningC
LearningC

Reputation: 3162

The output of the program will is,

5,20,5

because

if(bags[i]==20)
        return(bags+i);

returns pointer to bags[0] since bags[0]==20 and return is a pointer to it and

*next()=pos;

writes pos value to the address pointed by next() returned address, i.e. bags[0]=pos=5

Upvotes: 3

Related Questions