2

I am trying to get used to using pointers but i am struggling a bit whilde passing them into functions as parameters. I read that arrays are passed by reference to functions therefore a code like this can change the array elements(Assuming a valid array is given):

void f(int *b)
{
  b[2]=1;
}

in main:
f(validArray);

However even though we pass the pointer this doesn't seem to work;

void foo(int *b)
{
  b=b+2;
}

in main:
f(validArray);

doesn't move the pointer a step further. Why is that?

3 Answers 3

2

For starters arrays are non-modifiable lvalues. So you may not write for example

validArray = validArray + 2;

As for this pseudocode snippet

void foo(int *b)
{
    b=b+2;
}

in main:
foo(validArray);

then the pointer b is a local variable of the function. So within the function the value of b is changed due to this statement

    b=b+2;

But this does not have an effect on the passed argument.

Instead you could write

void foo( int **b )
{
    *b = *b + 2;
}

int main( void )
{
    int validArray[] = { 1, 2, 3, 4, 5 };

    int *p = validArray;
    foo( &p );
    printf( "%d\n", *p );
}

In C the term "passing by reference" means passing an object indirectly through a pointer to it. So dereferencing the pointer in a function you can change the pointed object. Pointers are the same objects. So if you want to change an original pointer you have to pass a pointer to the pointer.

Sign up to request clarification or add additional context in comments.

2 Comments

f( &p ); should be foo( &p );
@Jonaswg Thanks. It was a typo.
2

I read that arrays are passed by reference to functions

That's not quite right. When you pass an array to a function, a pointer is passed. Changing the pointer won't change the array. You can, however, change the array via the pointer. That's why the b[2]=1; works. b is still just a pointer that was passed as a copy though, so b=b+2; won't change the array.

It doesn't move the pointer a step further. Why is that?

It does move b ahead, but b is local to foo and is gone afterwards without changing the array. If you did this, for instance.

void foo(int *b)
{
    b=b+2;
    b[2]=1;
}

Then this will change validArray[4].

1 Comment

ohh because i am dereferencing the pointer b by using [] i can change the array indeed now i see.
2
b[2]=1;

is essentially

*(b+2) = 1;

which means its changing the data in the address (b+2)


b=b+2;

this means you are making b point to 2 elements next to what b was pointing before, which does not affect the data in the address of the pointer b, hence does not change the data in the array validArray

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.