在指针指向指针链的末尾初始化值

好吧,我一直在这一天(不是hw)开始,虽然它可能不是一个特别有用的代码,但这是一个巧妙的概念。 我试图找出最后设置值的最佳方法,因为缺少更好的名称,指向指针链的指针。 例如,我声明:

int *****ptr; 

将每个指针设置为指针段的最佳方法是什么,一直到实际的int值?

此代码无法编译,因为它不喜欢我使用和取消引用void指针的方式:

 #include  #include  #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; } 

是否有一些文章谈论指针的荒谬数量指针以及如何使用它们?

你拥有的非常接近。 不过,你可能想从内到外工作。 这是一个基于您的程序的完整示例(注释内联):

 #include  #include  #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; }