Reputation: 73
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
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
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
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