gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:56 25 4
gpt4 key购买 nike

下面的代码有一个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com