这肯定有问题吗?
#include <stdio.h>
#define NUM 1
#define NUM_SWARMS 3
typedef float coor_t[NUM];
typedef coor_t gBestX_t[NUM_SWARMS];
gBestX_t gBestX;
int main()
{
gBestX[0][1] = 3.0;
gBestX[1][1] = 3.0;
gBestX[8][1] = 4.0;
printf("%f\n", gBestX[8][1]);
return 0;
}
在我看来,这是将gBestX创建为一个大小为[1] [3]的2D数组,但是gcc和valgrind正在抱怨这个并得到正确的输出(4.0)。这不是违反数组的界限吗?
答案 0 :(得分:2)
如果启用该警告,gcc仅警告边界。有关详细信息,请参见gcc手册页:
-Warray-bounds
-Warray-bounds=n
This option is only active when -ftree-vrp is active (default for -O2 and above). It warns about
subscripts to arrays that are always out of bounds. This warning is enabled by -Wall.
-Warray-bounds=1
This is the warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must
be explicitly requested.
-Warray-bounds=2
This warning level also warns about out of bounds access for arrays at the end of a struct and for
arrays accessed through pointers. This warning level may give a larger number of false positives and
is deactivated by default.
答案 1 :(得分:0)
你需要一个更新的gcc。编译时我收到警告:
Bruces-MacBook-Pro:测试布鲁斯$ gcc -o t15 t15.c t15.c:13:4:警告:数组索引1超过数组的末尾(包含1个元素)[-Warray-bounds] gBestX [0] [1] = 3.0; ^〜 t15.c:9:1:注意:数组'gBestX'在这里声明 gBestX_t gBestX; ^ t15.c:14:6:警告:数组索引1超过数组的末尾(包含1个元素)[-Warray-bounds] gBestX [1] [1] = 3.0; ^〜 t15.c:9:1:注意:数组'gBestX'在这里声明 gBestX_t gBestX; ^ t15.c:15:8:警告:数组索引1超过数组的末尾(包含1个元素)[-Warray-bounds] gBestX [8] [1] = 4.0; ^〜 t15.c:9:1:注意:数组'gBestX'在这里声明 gBestX_t gBestX; ^ t15.c:17:25:警告:数组索引1超过数组的末尾(包含1个元素)[-Warray-bounds] printf(“%f \ n”,gBestX [8] [1]); ^〜 t15.c:9:1:注意:数组'gBestX'在这里声明 gBestX_t gBestX; ^ 产生了4个警告。