简体   繁体   English

在C:n维数组中取消引用非指针

[英]Dereferencing Non-Pointers in C: n-dimensional arrays

I was wondering if it is possible to reach the lowest level (the non-pointer level) of an n-dimensional array in C by conditionally dereferencing different layers of pointers until you reach a layer that is not pointers, as in the following example: 我想知道是否可以通过有条件地取消引用不同的指针层直到到达非指针层来达到C中n维数组的最低级别(非指针级别),如以下示例所示:

if(i_is_a_pointer){
  for(i = 0; i < some_given_length; i++){
    if((*i)_is_a_pointer){
      for(j = 0; j < some_given_length; j++){
        if((**i)_is_a_pointer)...etc.
      }
    }
  }
}

which would delve through the array either until it hit a non-pointer or exhausted the final block of code written. 这将遍历数组,直到遇到非指针或耗尽了最后编写的代码块为止。 How would one go about, in C, determining if the thing is a pointer (I would guess that sizeof would work, if the target non-pointer were of a different size than the memory address), and would the statement **i be a compile-time or run-time error if *i were not itself a pointer? 在C语言中,如何确定事物是否是指针(如果目标非指针的大小与内存地址的大小不同,我猜想sizeof会起作用),并且** i是如果* i本身不是指针,则是编译时还是运行时错误?

Additionally, which languages and techniques do you use/would you recommend for traversing the non-array elements of an n-dimensional array, where n is determined at run-time? 另外,在遍历n维数组的非数组元素时(在运行时确定n的情况下),您会/建议使用哪种语言和技术?

Multi-dimensional arrays in C aren't, as you seem to infer, nests of pointers until you reach the final level. 您似乎可以推断,C语言中的多维数组并不是嵌套的,直到达到最终级别为止。 They are just blocks of data. 它们只是数据块。 Outer dimensions automatically convert to pointers in certain contexts: The array converts to a pointer to its first element. 外部尺寸在某些情况下自动转换为指针:数组转换为指向其第一个元素的指针。 For example, 例如,

int a[3][4][5];

can also be written 也可以写

typedef int INNER[5];    // array of 5 ints
typedef INNER MIDDLE[4]; // array of 5 INNERs (not pointers)
typedef MIDDLE OUTER[3]; // array of 3 MIDDLEs (not pointers)
OUTER a;

Then these are also equivalent pointer conversions of arrays. 然后这些也是数组的等效指针转换。

MIDDLE *pm = a;
INNER *pi = a[0];
int *p = a[0][0];

and

int (*pm)[4][5] = a;
int (*pi)[5] = a[0];
int *p = a[0][0];

And finally since C is statically typed, there is no way or need to analyze types at run time as you are trying to do with your if statements. 最后,由于C是静态类型的,因此在尝试使用if语句时,没有方法或不需要在运行时分析类型。 In a compiled C program, there is essentually no type information remaining. 在已编译的C程序中,基本上没有剩余的类型信息。

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

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