Re: modify structure array pointer in the function
- From: Barry Schwarz <schwarzb@xxxxxxxxx>
- Date: Sun, 20 Nov 2005 19:59:16 -0800
On 20 Nov 2005 18:10:30 -0800, "s88" <dave.tw@xxxxxxxxx> wrote:
>Howdy:
> the follows is my program, I wanna change my structure array
>pointer in the function "testfunc", but I fail..., I also try to call
>the testfunc by reference, but the compiler says "test6.c:35: error:
>incompatible type for argument 1 of `testfunc'". Can I make my purpose
>in C?
>and how?
>
>
>typedef struct xxxx *xxxx_ptr;
>
>typedef struct xxxx{
> int just;
> long for_the;
> char *test;
>}xxxx;
>
>void testfunc(xxxx_ptr ptr){
C passes arguments by value. The ptr is this function is a copy of
the argument value in the calling statement.
> ptr++;
This updates the copy.
>}
The copy is destroyed as part of the process of exiting the function.
The updated value no longer exists.
>
>int main(void){
> xxxx XXXX[10];
> xxxx_ptr ptr = &XXXX[0];
> printf("%x\n",ptr);
%x expects an unsigned int. You are passing a pointer. This invokes
undefined behavior.
The only portable way to print a pointer value is to use %p and cast
the value to a void *.
> testfunc(ptr);
The value of an argument cannot be changed by the called program.
> printf("%x\n",ptr);
> return 0;
>}
The two usual solutions are:
Have the function return the updated value and call the function
in an assignment statement that assigns the new value to a suitable
variable.
Pass the address of the variable to be updated and let the
function update the variable by dereferencing the address.
<<Remove the del for email>>
.
- References:
- Prev by Date: Re: modify structure array pointer in the function
- Next by Date: Re: Hash function (str -> uint16)
- Previous by thread: Re: modify structure array pointer in the function
- Next by thread: Re: modify structure array pointer in the function
- Index(es):
Relevant Pages
|