简体   繁体   中英

Function setting up pointer on pointer

Why this work properly:

unsigned char* tab1;

int main()
{
   unsigned char* tab2;
   tab1 = new unsigned char[5];
   for(unsigned char i=0; i<5; i++){
       tab1[i] = i;
   }
   for(unsigned char x=0; x<5; x++){
       printf("%u\t",tab1[x]);
   }

   tab2 = tab1;

   for(unsigned char y=0; y<5; y++){
       printf("%u\t",tab2[y]);
   }
}

And this don't work:

unsigned char* tab1;

void fun(unsigned char* x){
    x = tab1;
}

int main()
{
   unsigned char* tab2;
   tab1 = new unsigned char[5];
   for(unsigned char i=0; i<5; i++){
       tab1[i] = i;
   }
   for(unsigned char x=0; x<5; x++){
       printf("%u\t",tab1[x]);
   }

   fun(tab2);

   for(unsigned char y=0; y<5; y++){
       printf("%u\t",tab2[y]);
   }
}

I can't assign pointer to pointer by function? If I can, how to do it? First version gave me 0 1 2 3 4, second 1 0 0 0 0, why?

fun(tab2) is essentially a no-op since all that function is doing is changing the value of the input parameter x that is passed by value: it does not change the value of tab2 in the caller.

The fact that you are using new is a red herring. Don't forget to call delete[] on the pointer returned back by new[] .

void fun(unsigned char* x)

You are passing the pointer by value. When x is modified it is the local copy on the stack, not tab2. To do that you need to pass the pointer by reference like void fun(unsigned char*& x)

This function

void fun(unsigned char* x){
    x = tab1;
}

and its call

unsigned char* tab2;
//...
fun(tab2);

can be imagined the following way

void fun( /* unsigned char* x */ ){
    unsigned char *inx = tab2;
    inx = tab1;
}

That is at first the local variable inx gets the value of the pointer tab2 and then its value is overwritten by the value of the pointer tab1 . Neither tab2 nor tab1 themselves were changed. tab2 had indeterminate value before the function call and it has the same value after the function call. It is the local variable inx that was changed.

Function parameters are function local variables. They get copies of values of corresponding arguments.

If you want to change an original object in a function you should pass it to the function by reference and correspondingly the parameter must be declared as having type as pointer to the type of the argument.

That is you could define the function the following way

void fun(unsigned char ** x){
    *x = tab1;
}

and call it like

fun( &tab2 );

or the following way

void fun(unsigned char * &x){
    x = tab1;
}

and call it like

fun( tab2 );

In this case the value of the original pointer tab2 would be changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM