Markus
Markus

Reputation: 73

Pass on function arguments by pointer

When function arguments are of the same type, is following code well-defined and portable?

void foo(int* p, int size);
void pass_on_args_by_pointer(int a, int b, int c)
{
    foo(&a, 3);
}

To clearify: the 'size' argument should contain the number of elements in the array p. So, I want to pass all three ints to foo.

Upvotes: 3

Views: 148

Answers (3)

user1952216
user1952216

Reputation: 75

void foo(int** p, int size)
{
   **p = size;
    return;
}
void pass_on_args_by_pointer(int *a, int b, int c)
{
   foo(&a, 3);
}

int main(void)
{
    int a = 0;
    pass_on_args_by_pointer(&a, 0, 0);
    printf("a = %d", a);

}

If you want to assign some value to varaiable a, you need to use pointer to pointer.

Upvotes: 0

jocke-l
jocke-l

Reputation: 703

Even if it would possibly work (In theory, it should, because the stack can be represented as an array), your compiler is not obligated to to pass the arguments on the stack. It could for example use registers instead to optimise your code, and then your code will break.

So trying to access another function's arguments this way would be undefined behavior.

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

No, this is neither portable nor well-defined. Compilers are not required to allocate function parameters in adjacent locations in memory. In fact, they are not required to place parameters b and c in memory at all, since you are not taking their address. Any access beyond the bounds of the int through p in foo is undefined behavior.

Upvotes: 7

Related Questions