-11

I have this code that gives a pointer an address and print it, but why that does not work??

void main()
{
int *b = (int*) 32;
printf("%d\n",b[0]);
}

2 Answers2

4

b[0] dereferences an array which points to memory you haven't allocated. The effects of doing this are undefined. You might get a value returned or your program may crash if address 32 isn't readable from your process.

simonc
  • 41,632
  • 12
  • 85
  • 103
  • how to make it readable ?! i wanna read that – mohamed esmael Jul 14 '13 at 11:21
  • Its platform dependant. If the OS decides the address is not readable, there's nothing you can do. Why do you want to read this particular location in memory? Or do you want to print the address of b rather than what it points to – simonc Jul 14 '13 at 11:28
0
int *b = (int*) 32;

above code assigns memory address 32 to this pointer, i don't think that is you want, you will get access denied error when you call printf, hope the following codes is useful toyou

int a = 32;
int *b = &a;
printf("%d\n",b[0]);
//output 32

printf( "%d\n", &b);
// output b pointer address.
Jenny 1985
  • 56
  • 3