【问题标题】:How to declare multiple pointer-to-pointer using while in C?如何在 C 中使用 while 声明多个指针到指针?
【发布时间】:2017-08-24 11:56:46
【问题描述】:

我有这个代码:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

void ft_ultimate_ft(int *********nbr)
{
    printf("%d", *********nbr);
}

int main(){
    /*Start of problem*/
    int *a;
    int **b = &a;
    int ***c = &b;
    int ****d = &c;
    int *****e = &d;
    int ******f = &e;
    int *******g = &f;
    int ********h = &g;
    int *********i = &h;
    /*end of problem*/
    *********i = 42;
    ft_ultimate_ft(i);
    return 0;
}

我需要在循环中包含指向指针的声明(例如,while)。需要减少声明的数量。

【问题讨论】:

  • 这是什么?谁提出了这个要求?
  • 为什么要这样做?无论如何,你可以循环值,而不是类型。
  • 您完全不担心a 是不确定的,因此车轮完全从您乘坐的马车上掉下来了?
  • 您不能循环执行此操作。星号的数量是类型的一部分,这个概念只存在于编译期间。

标签: c loops pointers while-loop


【解决方案1】:

我假设我已经正确理解了您的问题,即使用循环创建一个指向数字的多指针,然后为其赋值。

我写了一段代码,部分完成了你的要求,但仍然需要知道循环之后有多少层。

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
void ft_ultimate_ft(int *********nbr)
{
    printf("%d", *********nbr);
}

int main() {
    int t = 10;
    int n = 8;
    void * p = &t;
    for (int i = 0; i < n; i++)
    {
        void* * s = (void **)malloc(sizeof(void*));
        *s = p;
        p = s;
    }
    /*end of problem*/
    int *********real = (int *********)p;
    *********real = 42;
    ft_ultimate_ft(real);
    return 0;
}

哪个输出 42

程序的清理部分没有写

PS。在您的代码中,指针 a 是不确定的,我认为您的原始代码不能正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多