使用指针算法编写数组引用

时间:2015-01-29 11:27:44

标签: c arrays

让我们考虑以下代码片段:

#include<stdio.h>
main()
{
 int count[100][10];
 *(count + (44*10)+8)=99;
 printf("%d",count[44][8]);
}

它有什么问题?

3 个答案:

答案 0 :(得分:2)

count[44][8]

未初始化,您正在尝试打印它的值,即UB。

a[i][j] = *(a[i] + j); 
a[i][j] = *(*(a+i) + j);

因此,如果您想初始化count[44][8],请执行

*(count[44] + 8) = 10; /* or *(*(count + 44) + 8) = 10 */
printf("%d",count[44][8]);

答案 1 :(得分:2)

数组到指针衰减仅适用于一个级别;因此int count[100][10];衰减到int (*)[100]Why does int*[] decay into int** but not int[][]?)。

您可以将count投射到int*或使用&count[0][0]获取指向2D数组第一个元素的int*指针。

答案 2 :(得分:1)

*(count + (44*10)+8)=99;应该是

*(count[0] + (44*10)+8)=99;

countp[0]的类型可以根据需要重新解释为int *

Live code here

count的类型为int [100][10],因此向其中添加一些大号将提前10次,并且访问该位置将导致UB。

Anopter的写作方式是:

*( *(count + 44) + 8 )=99;