0

I have a general question about pointers. Like if I call a function and for example the first argument is a pointer. If I change the pointer-address in the function with pointer++, do I change the pointer in general or is it just like a copy and in the function which called it the pointer has the same address like before calling.

I hope it's understandable :)

Thanks

Jan Wolfram
  • 145
  • 8
  • There is no such thing in `C` call by reference, you have to mimic it by passing address. That is you need pointer to pointer. – kiran Biradar Nov 28 '19 at 11:18

2 Answers2

1

In C all arguments are passed by value, even pointers. That means if you pass a pointer to a function the pointer is copied, and the function will have a local copy that it can modify as it likes without affecting the original pointer.

Example:

#include <stdio.h>

void print_pointer_plus_one(const char *pointer)
{
    ++pointer;  // Make pointer point to the next element
    printf("In call: %s\n", pointer);
}

int main(void)
{
    const char* hello = "hello";

    printf("Before call: %s\n", hello);
    print_pointer_plus_one(hello);
    printf("After call: %s\n", hello);
}

The above program should print

Before call: hello
In call: ello
After call: hello

The function you call could modify the data that the pointer is pointing to, and this will affect the data itself and not the pointer. This can be used to emulate pass by reference:

#include <stdio.h>

void modify_data(char *pointer)
{
    pointer[0] = 'M';  // Modify the data that pointer is pointing to
}

int main(void)
{
    char hello[] = "hello";

    printf("Before call: %s\n", hello);
    modify_data(hello);
    printf("After call: %s\n", hello);
}

This program will print

Before call: hello
After call: Mello
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

To change an object in a function you have to pass the object by reference through a pointer. So if you want to change an original pointer in a function you have to pass to the function a pointer to the pointer.

For example

#include <stdio.h>

void f( int **p )
{
    static int x = 20;

    *p = &x;
}

int main( void )
{
    int x = 10;
    int *p = &x;

    printf( "The address of p is %p, and the pointed value is %d\n",
            ( void * )p, *p );

    f( &p );

    printf( "The address of p is %p, and the pointed value is %d\n",
            ( void * )p, *p );

}

The program output might look like

The address of p is 0x7ffd9c8d023c, and the pointed value is 10
The address of p is 0x600998, and the pointed value is 20
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335