C 指针和数组:[警告] 赋值使指针来自整数而不进行强制转换 [英] C pointers and arrays: [Warning] assignment makes pointer from integer without a cast
问题描述
我在使用 C 中的指针和数组时遇到了一些问题.代码如下:
#includeint *ap;int a[5]={41,42,43,44,45};整数 x;int main(){ap = a[4];x = *ap;printf("%d",x);返回0;}
当我编译并运行代码时,我收到此警告:
<块引用>[警告] 赋值使指针从整数而不进行强制转换[默认启用]
对于第 9 行(ap = a[4];),终端崩溃.如果我将第 9 行更改为不包含位置 (ap = a;),则不会收到任何警告并且可以正常工作.为什么会这样?我觉得答案很明显,但我就是看不到.
在这种情况下 a[4]
是数组 a<中的
>5
整数/code>,ap
是一个指向整数的指针,因此您将一个整数分配给一个指针,这是警告.
所以 ap
现在持有 45
并且当您尝试取消引用它时(通过执行 *ap
),您正在尝试访问地址 45 处的内存,这是一个无效地址,因此您的程序会崩溃.
你应该做 ap = &(a[4]);
或 ap = a + 4;
在 c
中,数组名称衰减为指针,因此 a
指向数组的第一个元素.
这样,a
等价于 &(a[0])
.
I'm having some trouble with pointers and arrays in C. Here's the code:
#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;
}
When I compile and run the code I get this warning:
[Warning] assignment makes pointer from integer without a cast [enabled by default]
For line number 9 (ap = a[4];) and the terminal crashes. If I change line 9 to not include a position (ap = a;) I don't get any warnings and it works. Why is this happening? I feel like the answer is obvious but I just can't see it.
In this case a[4]
is the 5th
integer in the array a
, ap
is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap
now holds 45
and when you try to de-reference it (by doing *ap
) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.
You should do ap = &(a[4]);
or ap = a + 4;
In c
array names decays to pointer, so a
points to the 1st element of the array.
In this way, a
is equivalent to &(a[0])
.
这篇关于C 指针和数组:[警告] 赋值使指针来自整数而不进行强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!