在指针的结束初始化值的指针的指针链 [英] Initializing values at the end of a pointer to pointer to pointer chain

查看:142
本文介绍了在指针的结束初始化值的指针的指针链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我在这已经起动了所有日子(不HW),虽然它可能不是code的一个特别有用的一点,这是一个整洁的概念性的东西。我试图找出最好的方式在年底设定的值,由于缺乏一个更好的名字,一个指向指针的指针链。例如,我宣布:

Alright I've been cranking away at this all day (not hw), and though it may not be a particularly useful bit of code, it is a neat conceptual thing. I am trying to figure out the best way to set a value at the end of, for lack of a better name, a pointer to pointer to pointer chain. For example, I declare:

int *****ptr;

什么是设置每个指针指向细分市场的最佳途径,下至实际int值一路?

What is the best way to set each pointer to pointer segment, all the way down to the actual int value?

这code不编译,因为它不喜欢我用的方式,取消引用空指针:

This code doesn't compile because it doesn't like the way I use and dereference void pointers:

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

#define NUMPOINTERS 5

int main(int argc, char **argv)
{
    int *****number;
    *****number = malloc(sizeof(void*));
    void *ptr = *number;

    int i;

    for(i = 1; i < NUMPOINTERS; i++)
    {
        if(i == NUMPOINTERS - 1)
        {
            ptr = malloc(sizeof(int));
            int *iPtr = (int*)ptr;
            *iPtr = 900;
            break;
        }

        *ptr = malloc(sizeof(void*));
        ptr = **ptr;
    }

    printf("%d", *****number);

    return 0;

}

有一些文章在那里,大约荒谬的数字指针的指针,以及如何谈判,与他们合作?

Is there some article out there that talks about ridiculous numbers of pointers to pointers and how to work with them?

推荐答案

你有什么是pretty接近。你可能想从里面出来工作,虽然。下面是根据你的程序(注释内嵌)一个完整的例子:

What you have is pretty close. You probably want to work from the inside out, though. Here's a complete example based on your program (comments inline):

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

#define NUMPOINTERS 5

int main(void)
{
    void *ptr = malloc(sizeof(int)); // allocate space for the integer value
    *(int *)ptr = 900;               // initialize it 

    // iterate to create the nested pointers
    for (int i = 1; i < NUMPOINTERS; i++)
    {
        void **newptr = malloc(sizeof(void *)); // create a new pointer
        *newptr = ptr;                          // point it at what we have so far
        ptr = newptr;                           // "step out" one level
    }

    int *****number = ptr;        // make our 'int *****' pointer
    printf("%d\n", *****number);  // dereference and print the pointed-to value

    return 0;
}

这篇关于在指针的结束初始化值的指针的指针链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆