简体   繁体   English

将平面指针转换为多维数组

[英]Casting a flat pointer to a multidimensional array

Is it possible to get the compiler to do the same pointer arithmetic on flat pointers as it does on multidimensional arrays? 是否有可能使编译器对平面指针执行与多维数组相同的指针算术运算?

With multidimensional arrays, the pointer arithmetic appears to work as follows: 对于多维数组,指针算法的工作方式如下:

int main(void)
{
    char ar[2][3][4];
#define At(a,x,y,z) printf("["#x"]["#y"]["#z"]=%ld\n", &(a)[x][y][z] - &(a)[0][0][0]);
    At(ar,0,0,0);
    At(ar,0,0,1);
    At(ar,0,0,2);
    At(ar,0,0,3);
puts("");
    At(ar,0,1,0);
    At(ar,0,2,0);
    At(ar,0,3,0);
puts("");
    At(ar,1,0,0);
    At(ar,2,0,0);
    At(ar,3,0,0);
/*
    [0][0][0]=0
    [0][0][1]=1
    [0][0][2]=2
    [0][0][3]=3

    [0][1][0]=4  // 1 * 4
    [0][2][0]=8  // 2 * 4
    [0][3][0]=12 // 3 * 4

    [1][0][0]=12 // 1 * 3 * 4
    [2][0][0]=24 // 2 * 3 * 4
    [3][0][0]=36 // 3 * 3 * 4 
*/
}

So I tried: 所以我尝试了:

    char *blk;
    if(!(blk=malloc(1000))) return -1;
    char (*p)[2][3][4] = (char(*)[2][3][4])blk;

    At(p,0,0,0);
    At(p,0,0,1);
    At(p,0,0,2);
    At(p,0,0,3);
puts("");
    At(p,0,1,0);
    At(p,0,2,0);
    At(p,0,3,0);
puts("");
    At(p,1,0,0);
    At(p,2,0,0);
    At(p,3,0,0);

/*
    [0][0][0]=0
    [0][0][1]=1
    [0][0][2]=2
    [0][0][3]=3

    [0][1][0]=3
    [0][2][0]=6
    [0][3][0]=9

    [1][0][0]=6
    [2][0][0]=12
    [3][0][0]=18
*/
}

But as you can see, this doesn't give corresponding results. 但是正如您所看到的,这不会给出相应的结果。 What exactly is going on here? 这到底是怎么回事? Can the results be made to match? 结果可以匹配吗?

You added an extra dimension, try this instead: 您添加了额外的维度,请尝试以下操作:

char (*p)[3][4] = (char(*)[3][4])blk;

Also note that your printf format is incorrect: the difference of 2 pointers has type ptrdiff_t , the corresponding format length modifier is t : 另请注意,您的printf格式不正确:2个指针的差值为ptrdiff_t ,相应的格式长度修饰符为t

#define At(a,x,y,z) printf("["#x"]["#y"]["#z"]=%td\n", &(a)[x][y][z] - &(a)[0][0][0]);

If your C library is not fully C99 compliant, you should use a cast: 如果您的C库不完全符合C99,则应使用强制转换:

#define At(a,x,y,z) printf("["#x"]["#y"]["#z"]=%ld\n", (long)(&(a)[x][y][z] - &(a)[0][0][0]));

I think you are missing a dereference. 我认为您缺少取消引用。 You now have a pointer to a 3 dimensional array. 现在,您有一个指向3维数组的指针。

You need to do this: 您需要这样做:

At(*p, 0, 0, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM