Home > other >  C pointer to a pointer confusion
C pointer to a pointer confusion

Time:05-10

I have the following code. I tried to change the value of y by using a pointer to a pointer (i.e. trying to do a de-referencing twice from the pointer that points to another pointer). this is my code, but for some reasons it doesn't work, could someone tells me where I have done wrong:

#include <stdio.h>
void changeAddr(int **j) {
    (*j)  ;
    printf("change pointer's address to: %p\n", j);
    (**j)  ; // is there something wrong with this part?  I want to increase the 
            // value pointed to by the pointer pointed to by j (so I thought
            // it would be the value of y in main, but there is an error message
            // the error says: *** stack smashing detected ***: terminated
    printf("change the value pointed to by the pointer by using a pointer: 
\n", **j); // this does not 
    // give value 7 for some reasons
}
void inval(int *i) {
    (*i)  ;
    printf("address of i: %p\n", i);
    printf("just increased: 
 \n", *i);
    changeAddr(&i);
}



int main()
{
    printf("Hello World\n");
    int y = 5;
    inval(&y);
    //printf("
\n", y);
    printf("%p\n", &y);
    printf("value of y in the end: %d\n", y);
    

    return 0;
}



CodePudding user response:

    int y = 5;
    inval(&y);

    /* inside intval(int *i): i points to a single int */
    (*i)  ;  // Increments y
    changeAddr(&i);

    /* inside changeaddr(int **j): j points to a pointer to a single int */
    (*j)  ; // Increments i; i now points to the next thing after y;
            // the spec says we can always do this but dereferencing it is undefined
    (**j)  ; // Increments the next thing after y; oops that's undefined behavior */
  • Related