【问题标题】:What happens when we use array[i,j] to access elements in c? [duplicate]当我们使用 array[i,j] 访问 c 中的元素时会发生什么? [复制]
【发布时间】:2018-09-18 03:54:03
【问题描述】:

在 C 中,要访问二维数组,我们使用格式 array[i][j]。但是当我不小心输入了 array[i, j] 时,它仍然编译并返回一个小的整数值(35 代表 i = 5 和 j = 7,0 代表 i = 5 和 j = 8)。 我知道对于二维数组,使用单个 [i] 将返回第 i 个元素的地址,但是即使对于具有 GB 内存的现代系统,地址值也可以这么小吗?此外,GCC 是如何编译和解释 [i , j] 的? 我在 Windows 10 64 位系统上使用 GCC 和 Cygwin 终端。 这是声明:

printf("\n With maximum weight : %d", table[no_of_items , w]);

【问题讨论】:

标签: c arrays pointers gcc


【解决方案1】:

当我们使用 array[i,j] 访问 c 中的元素时会发生什么?

i 被评估,然后其结果值被忽略。 j 被评估并用于索引array[]。很像:

// printf("\n With maximum weight : %d", table[no_of_items , w]);

(void) no_of_items;
printf("\n With maximum weight : %d", table[w]);
no_of_items , w 中使用的

,逗号运算符@Shawn


如果table[] 是一个二维数组,则printf() 中的table[w] 将产生一个指针。启用良好的编译器会发出警告。也许与

警告:格式“%d”需要“int”类型的参数,但参数 2 的类型为“int *”[-Wformat=]

int table[5][7];
int i = 2;
int j = 3;
printf("\n With maximum weight : %d", table[i,j]);

GCC 是如何编译的

使用不匹配的说明符和参数是未定义的行为 (UB)。编译器假设编码器知道他们在做什么。省时间。启用所有警告。

地址值能这么小吗

当然,但不那么相关,因为不匹配是 UB。打印的可能是指针为int,部分指针为int,与指针无关,电话号码8675309。是UB。

【讨论】:

    猜你喜欢
    • 2015-01-09
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多