C指针和数组:【警告】赋值时将整数指针,未作投 [英] C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

查看:108
本文介绍了C指针和数组:【警告】赋值时将整数指针,未作投的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些麻烦,在C.指针和数组这里是code:

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;
}

当我编译和运行code我得到这样的警告:

When I compile and run the code I get this warning:

【警告】赋值时将整数指针,未作投
  [默认启用]

[Warning] assignment makes pointer from integer without a cast [enabled by default]

有关行号9(AP =一个[4])和终端崩溃。如果我改变9号线不包括位置(AP =一;)我没有得到任何警告和它的作品。这究竟是为什么?我觉得答案是显而易见的,但我不能看到它。

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.

推荐答案

在这种情况下, A [4] 4 数组中的整数 A AP 是整数的指针,所以你分配给一个整数指针,这就是警告。照片所以 AP 现在持有 45 ,当你试图去参考它(通过执行 * AP )你想在地址45,这是一个无效的地址来访问内存,所以你的程序崩溃。

In this case a[4] is the 4th 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.

您应该做的 AP =放大器(A [4]); AP = A + 4;

C 数组名衰变为指针,所以 A 指向数组的第一个元素。
这样, A 等同于&功放;(A [0])

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆