在 C 中的指针数组中搜索值的编译器依赖性

标签 c arrays pointers 2d

下面的代码有一个名为 ReadOnly[] 的数组,它包含指向其他数组的元素,如 AV_ReadOnlyBV_ReadOnly 等。 AV_ReadOnlyBV_ReadOnly 等是包含指向整数数组的元素的指针数组。

read_arrays() 是一个用于打印特定列表/访问整数数组的任何特定值的函数。这种方法在测试环境中运行良好。但是,随着平台/编译器的改变,这种方法是否有可能失败?

#include<stdio.h>

int AV1_ReadOnly[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int AV2_ReadOnly[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

int BV1_ReadOnly[] = { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
int BV2_ReadOnly[] = { 31, 32, 33, 34, 35, 36, 37, 38, 39, 40};

int MV1_ReadOnly[] = { 41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
int MV2_ReadOnly[] = { 51, 52, 53, 54, 55, 56, 57, 58, 59, 60};

int NC1_ReadOnly[] = { 61, 62, 63, 64, 65, 66, 67, 68, 69, 70};
int NC2_ReadOnly[] = { 71, 72, 73, 74, 75, 76, 77, 78, 79, 80};

int * AV_ReadOnly[] =
{
  AV1_ReadOnly,
  AV2_ReadOnly,
};

int * BV_ReadOnly[] = 
{
   BV1_ReadOnly,
   BV2_ReadOnly,
};  

int * MV_ReadOnly[] =
{
  MV1_ReadOnly,
  MV2_ReadOnly,
};

int * NC_ReadOnly[] = 
{
   NC1_ReadOnly,
   NC2_ReadOnly
};  

int ** ReadOnly[] =
{
   AV_ReadOnly,
   BV_ReadOnly,
   MV_ReadOnly,
   NC_ReadOnly
};


void read_arrays( int obj, int inst )
{
int ** ArrayPtr = ReadOnly[obj];

 int count =0;
   while( count <8 )
   {
      printf( "\n %d", *(ArrayPtr[inst]+count) );
      count++;
   }
}


void main()
{
   read_arrays( 1,1 );
}

最佳答案

只要将 int 数组和 int* 数组保存在同一个文件中就应该没问题。

此外,如果您无意更改它们,您可以(应该)将它们声明为 const

此外,如果您不打算在其他文件中extern它们,则可以(应该)将它们声明为static

顺便说一句,从您发布的内容来看,您似乎可以简单地使用 int table[8][10] 代替...

关于在 C 中的指针数组中搜索值的编译器依赖性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21279480/

相关文章:

c - 停止 for 循环

javascript - VueJS 在 v-for 中仅选择一个元素

c++ - 如何获取类成员函数指针

c++ - 0x742808F2 处未处理的异常:Microsoft C++ 异常:内存位置 0x0055E9E4 处的 std::out_of_range

c - 为什么 while 循环在 else 语句之前停止?

c - GHC 运行时如何处理文件 I/O?

c - 分而治之——返回一个数组

javascript - 遍历数组并将每个值附加到列表中

python - 强制 NumPy ndarray 获取其在 Cython 中的内存所有权

c++ - 在非 void 函数中我不想返回任何内容