C++指针到指针到指针的乘法不起作用

C++ pointer to pointer to pointer multiplication not working

本文关键字:指针 不起作用 C++      更新时间:2023-10-16

这可能是一个非常简单的问题,但无论如何:我使用的是VS 2010,我想要的是在最后得到x****y的结果。这是我的代码:

#include <iostream>
using namespace std;
void main()
{
    int x = 5;
    int *** y= new int**;
    ***y = 5;
    cout << x****y << endl;
    system("pause");
}

这只会让程序崩溃,我不知道为什么。这是我得到的错误日志:

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

此外,是否有一种方法可以在不动态分配**y内存的情况下实现相同的结果?非常感谢。

您的代码正在动态地分配一个ptr到ptr到int,但不是它需要指向的嵌套ptr和int

    #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");
    }

要在不动态分配内存的情况下做到这一点,您需要这样的东西:

    #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");
    }

没有任何动态分配:

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

如果没有动态、静态或自动分配,就无法做到这一点;指针需要指向某个对象。

Y未初始化。

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