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

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.

This question is related to c arrays pointers warnings

The answer is


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


What are you doing: (I am using bytes instead of in for better reading)

You start with int *ap and so on, so your (your computers) memory looks like this:

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

lets take a look waht happens when (print short cut for ...print("$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)

and so on, so a[0] is the same as *a, a[1] = *(a+1), ....

a[n] just reads easier.

now, what happens at line 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

So the "warning" is not just a warning it's a severe error.


int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to pointers

Method Call Chaining; returning a pointer vs a reference? lvalue required as left operand of assignment error when using C++ Error: stray '\240' in program Reference to non-static member function must be called How to convert const char* to char* in C? Why should I use a pointer rather than the object itself? Function stoi not declared C pointers and arrays: [Warning] assignment makes pointer from integer without a cast Constant pointer vs Pointer to constant How to get the real and total length of char * (char array)?

Examples related to warnings

numpy division with RuntimeWarning: invalid value encountered in double_scalars libpng warning: iCCP: known incorrect sRGB profile How to use _CRT_SECURE_NO_WARNINGS C pointers and arrays: [Warning] assignment makes pointer from integer without a cast Server configuration by allow_url_fopen=0 in IntelliJ IDEA shows errors when using Spring's @Autowired annotation Warning :-Presenting view controllers on detached view controllers is discouraged Data truncated for column? Warning message: In `...` : invalid factor level, NA generated How to suppress warnings globally in an R Script