C指针和数组:[Warning]赋值使整数指针不带强制转换

use*_*889 18 c arrays warnings pointers

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

#include<stdio.h>


int *ap;
int a[5]={41,42,43,44,45};
int x;

int main()
{
    ap = a[4];
    x = *ap;
    printf("%d",x);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Dip*_*pto 25

在这种情况下a[4]5th在阵列中的整数a,ap是整数的指针,所以你分配给一个指针的整数,这就是警告.
所以ap现在保持45并且当您尝试取消引用它(通过执行*ap)时,您尝试访问地址45处的内存,这是一个无效的地址,因此您的程序崩溃.

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

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


hal*_*bit 8

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

你开始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
Run Code Online (Sandbox Code Playgroud)

让我们一起来看看(打印短切...打印("$ 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)
Run Code Online (Sandbox Code Playgroud)

等等,所以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
Run Code Online (Sandbox Code Playgroud)

所以"警告"不仅仅是一个警告,它是一个严重的错误.