Re: modify structure array pointer in the function



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>>
.



Relevant Pages

  • Re: Unions Redux
    ... pointer casting. ... union U {double a; unsigned int b;} u; ... valid and aliasing rules don't work here. ...
    (comp.lang.c)
  • Re: Initializer element not constant
    ... unsigned int, which I assume is 32 bits, would cause a nasty run-time ... problem, since first if any of the upper 32 bits of the pointer are 1, ... an object of this type with static storage duration you are trying to ... So your compiler, with one set of options, is quite free to reject ...
    (comp.lang.c)
  • Re: unsigned __int64 typecast bug?
    ... The typecast does the correct thing for an unsigned int, ... I don't know if the conversion sequence from 32 bit pointer to 64 bit ... The compiler will sign-extend the pointer when it is assigned ...
    (microsoft.public.vc.language)
  • Re: Please help me to clarify the invalid values of unary operator *
    ... for an int. ... implementation unsigned int has no trap representations. ... with arithmetic on a character pointer, we have created a pointer to ... operating system, if there is one, to respond. ...
    (comp.std.c)
  • Re: Unions Redux
    ... pointer casting. ... and what's passed to memcpy(). ... aliasing rules. ... union U {double a; unsigned int b;} u; ...
    (comp.lang.c)