简体   繁体   中英

c++ pointer to pointer and call function that receive pointer to pointer

The question is how to call function that request pointer to pointer if we are already at the function that operate with pointer to pointer . I tried some variants but all of them compile with error (SIGSEGV) http://rextester.com/ZSW68923

void test_sessiontwo ( int **ptr_to_ptr )
{
    std::cout << *ptr_to_ptr;    
}

void test_session ( int **ptr_to_ptr )
{
    std::cout << "Hello, world2!\n" << *ptr_to_ptr;    
    **ptr_to_ptr = 20;
     test_sessiontwo   ( ptr_to_ptr ); // ERROR. HOW TO CALL THIS???
}

int main()
{
    int* ptr_int;
    *ptr_int = 10;
    test_session ( &ptr_int );   

    std::cout << "Hello, world!\n";
}

This code segment

   int* ptr_int;
    *ptr_int = 10;

is already wrong. Pointer ptr_int was not initialized. So the program has undefined behaviour.

To test your code you could write for example

int main()
{
    int* ptr_int = new int( 10 );
    test_session ( &ptr_int );   

    std::cout << "Hello, world!\n";

    delete ptr_int;
}

Try

int i=10;
int *ptr_int = &i;
test_session(&ptr_int);

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