Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 327
user2274889 Avatar asked Feb 18 '14 15:02

user2274889


2 Answers

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

like image 135
Dipto Avatar answered Oct 03 '22 05:10

Dipto


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.

like image 31
halfbit Avatar answered Oct 03 '22 05:10

halfbit