Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Incrementing pointer address passed to a function ++ operator

I have a question that is raised from this discussion: C - modify the address of a pointer passed to a function

Let's say I have the following code:

#include <stdio.h>
foo(char **ptr){
    *ptr++;
}

int main()
{

    char *ptr = malloc(64);
    char arr[] = "Hello World!";
    memcpy(ptr, arr, sizeof(arr)); 
    foo(&ptr);
    foo(&ptr);
    printf("%s",ptr);
    return 0;
}

I was wondering what the output of this program would be and I thought that it should be llo World!.

After some investigation I found the question linked above and realized that, in C, parameters to functions are always passed by value. So far there was no problem. When it comes to change *ptr++; expression to -> *ptr = *ptr +1; output becomes: llo World!.

At this point, I can say that I am a little confused. In order to change pointer address, we need a double pointer. That is fine, but why do post increment operations differ? Is it because of the operator precedence?

Here I tried the example in an online C compiler.

like image 891
asevindik Avatar asked Nov 16 '21 17:11

asevindik


People also ask

Can we increment function pointer?

When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.

Can we increment a function?

Increment() Function It takes a variable and increments (changes) its value, and also returns this value. The increment can be a positive or negative number. Note: The Increment() function changes the value of its first argument.

How do you increment a pointer to an integer?

Try using (*count)++ . *count++ might be incrementing the pointer to next position and then using indirection (which is unintentional).


Video Answer


2 Answers

The postfix increment operator ++ has higher precedence than the dereference operator *. So this:

*ptr++;

Parses as:

*(ptr++);

So it changes the parameter value itself, not what it points to. You instead want:

(*ptr)++;
like image 149
dbush Avatar answered Oct 26 '22 19:10

dbush


Postfix operators have higher priority than unary operators. So this expression

*ptr++

is equivalent to

*( ptr++ )

The value of the sub-expression ptr++ is the value of the pointer before its incrementing.

So actually you are incrementing the parameter ptr having the type char **. So this incrementing does not change the original pointer and does not make a sense.

Instead you could write

( *ptr )++

But it will be more clear and less confusing to use the unary increment operator like

++*ptr

if you want to increment the original pointer itself.

like image 25
Vlad from Moscow Avatar answered Oct 26 '22 19:10

Vlad from Moscow