C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

Total
0
Shares

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.


Solution

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]).

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *