C指针和数组:赋值使得整数指针没有强制转换

我在使用C中的指针和数组时遇到了一些问题。这是代码:

#include int *ap; int a[5]={41,42,43,44,45}; int x; int main() { ap = a[4]; x = *ap; printf("%d",x); return 0; } 

当我编译并运行代码时,我收到此警告:

[警告]赋值使得整数指针没有强制转换[默认启用]

对于第9行(ap = a [4];)并且终端崩溃。 如果我将第9行更改为不包含某个位置(ap = a;),我不会收到任何警告并且它有效。 为什么会这样? 我觉得答案很明显,但我看不出来。

在这种情况下a[4]是数组a4th整数, ap是指向整数的指针,因此您要为指针指定一个整数,这就是警告。
因此ap现在保持45并且当你尝试取消引用它时(通过执行*ap )你试图访问地址45的内存,这是一个无效的地址,所以你的程序崩溃了。

你应该做ap = &(a[4]);ap = a + 4;

c数组名称衰减到指针,所以指向数组的第一个元素。
这样, a等于&(a[0])

你在做什么:(我使用字节而不是更好的阅读)

你从int *ap开始,依此类推,所以你的(你的计算机)内存如下所示:

 -------------- memory used by some one else -------- 000: ? 001: ? ... 098: ? 099: ? -------------- your memory -------- 100: something <- here is *ap 101: 41 <- here starts a[] 102: 42 103: 43 104: 44 105: 45 106: something <- here waits x 

让我们一起来看看(打印短切...打印(“$ d”,...)

 print a[0] -> 41 //no surprise print a -> 101 // because a points to the start of the array print *a -> 41 // again the first element of array print a+1 -> guess? 102 print *(a+1) -> whats behind 102? 42 (we all love this number) 

等等,所以a [0]与* a,a [1] = *(a + 1),....

a [n]只是阅读起来更容易。

现在,第9行会发生什么?

 ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45 // warning! converting int to pointer! -------------- your memory -------- 100: 45 <- here is *ap now 45 x = *ap; // wow ap is 45 -> where is 45 pointing to? -------------- memory used by some one else -------- bang! // dont touch neighbours garden 

所以“警告”不仅仅是一个警告,它是一个严重的错误。

int[]int*以相同的方式表示,除了int []分配(IIRC)。

ap是一个指针,因此给它一个整数的值很危险,因为你不知道地址45是什么。

当您尝试访问它( x = *ap )时,您尝试访问地址45,这会导致崩溃,因为它可能不是您可以访问的内存的一部分。