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

标签 c arrays pointers gcc

<分区>

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

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

最佳答案

What happens when we use array[i,j] to access elements in 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] 将产生一个指针。启用良好的编译器会发出警告。也许与

warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]

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

how did GCC compile

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

can the address value be so small

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

关于c - 当我们使用 array[i,j] 访问 c 中的元素时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52378666/

相关文章:

c - 将匿名 PIPE HANDLE 传递给子进程

c - C中的指针传递

c - 双指针作为函数参数

C 编程 - 线程,以及什么是 void (*func)(void*, unsigned long)

c - 字母表的嵌套循环

c++ - 计算相邻矩形的数量

javascript - 如何对字符串和对象使用 findIndex

c# - 以这种特定方式随机排列数组?

arrays - 在 Swift 中,我可以使用 for-in 枚举来初始化或重置数组吗?

c++ - 如何调用函数指针数组中的函数?