好吧,我整天都在研究这个(不是硬件),虽然它可能不是一段特别有用的代码,但它是一个简洁的概念性东西。由于缺少更好的名称,我试图找出在指向指向指针链的指针的指针末尾设置值的最佳方法。例如,我声明:
int *****ptr;
将每个指针设置为指针段的最佳方法是什么,一直到实际的 int 值?
此代码无法编译,因为它不喜欢我使用和取消引用 void 指针的方式:
#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;
}
是否有一些文章讨论了指向指针的指针的荒谬数量以及如何使用它们?
最佳答案
您所拥有的非常接近。不过,您可能希望从内到外工作。这是一个基于您的程序的完整示例(内嵌注释):
#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;
}
关于c - 在指向指针链的指针末尾初始化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15915046/