简体   繁体   中英

C++ pointer to pointer to pointer multiplication not working

This might be quite a simple question but anyways: I'm using VS 2010 and what I want is to obtain the result of x****y at the end. This is my code:

#include <iostream>
using namespace std;

void main()
{
    int x = 5;
    int *** y= new int**;
    ***y = 5;
    cout << x****y << endl;
    system("pause");
}

This just makes the program crash and I can't figure out why. This is the error log I get:

    1>------ Build started: Project: Stuffing around, Configuration: Debug Win32 ------
    1>  main.cpp
    1>  LINK : D:\Programming Projects\Stuffing around\Debug\Stuffing around.exe not found or not built by the last incremental link; performing full link
    1>  Stuffing around.vcxproj -> D:\Programming Projects\Stuffing around\Debug\Stuffing around.exe
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

Also, would there be a way to achieve the same results without dynamically allocating memory at **y? Thanks a lot.

Without any dynamic allocation:

int x = 5;    
int i;
int *pi = &i;
int **ppi = &pi;
int ***y = &ppi;
***y = 5;
cout << x****y << endl;

You can't do it without either dynamic, static, or automatic allocation; a pointer needs something to point to.

Your code is dynamically allocating a ptr to ptr to int, but not the nested ptr and int it would need to point to. (hope all the indirection made sense) To do this with dynamic memory your going to need something like this:

    #include <iostream>
    using namespace std;

    void main()
    {
        int x = 5;
        int *** y= new int**;
        *y = new int *
        **y = new int
        ***y = 5;
        cout << x* (***y) << endl;
        system("pause");
    }

To do it without dynamically allocating memory you would need something like this:

    #include <iostream>
    using namespace std;

    void main()
    {
        int x = 5;
        int y = 5;
        int *y_ptr = &y;
        int **y_ptr_ptr = &y_ptr;
        int ***y_ptr_ptr_ptr = &y_ptr_ptr;
        cout << x* (***y_ptr_ptr_ptr) << endl;
        system("pause");
    }

Y is not initialized.

y = new int**;
*y = new int*;
**y = new int;
***y = 5;

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