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

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


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 *ap101: 41                 <- here starts a[] 102: 42103: 43104: 44105: 45106: something          <- here waits x

lets take a look waht happens when (print short cut for ...print("$d", ...)

print a[0]  -> 41   //no surpriseprint a     -> 101  // because a points to the start of the arrayprint *a    -> 41   // again the first element of arrayprint a+1   -> guess? 102print *(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 45x = *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.