0

I am trying to give a value to a pointer. this code works fine

int i =5;   
int *ptr ;   
ptr = &i;   
printf(" %d\n",*ptr);   

but this code shows an error

int i =5;   
int *ptr ;   
*ptr = 5;   
printf(" %d\n",*ptr);   

can someone explain this to me?

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
user1598764
  • 25
  • 1
  • 7

4 Answers4

2

int *ptr gets initialized to a random location, which possibly points to invalid memory, and you try to write 5 to that location.

rand
  • 698
  • 5
  • 13
  • So how can i do it without using any other variable( "i" in code)? – user1598764 Nov 14 '13 at 18:43
  • Well, you can't. If you want to write to a location by dereferencing (i.e. doing `*ptr`) the pointer, the pointer needs to point to a valid location, and to get a valid location you have to allocate a variable first (e.g. `int i = 5;`). An alternative would be to use dynamic memory, but I don't think that's what you need. I think I need to know why you want to do that (instead of using a regular variable) to tell you how you can do what you want to do :) – rand Nov 15 '13 at 08:26
2

When you declare int *ptr, you're creating a variable called ptr which can hold the address of an int. When you dereference it in *ptr = 5, you're saying "store 5 in the address that ptr points to" - but as ptr is uninitialised, where it points to is undefined. So you're invoking undefined behaviour.

An int * does not store an int, but just an address that points to one. There still has to be a real int at that address.

If you want to allocate an int that exists outside of the local scope, you can use malloc. A simple conversion of your example without error checking:

int *ptr = malloc(sizeof(int));
*ptr = 5;
printf(" %d\n",*ptr);

If you do use malloc, just remember to free the allocated memory when you're finished:

free(ptr);
James M
  • 18,506
  • 3
  • 48
  • 56
0

The second version assigns 5 to the memory pointed to by ptr, but you haven't yet initialized ptr to point to a known location.

So it writes the value to the memory at whatever address happens to be in ptr, which is whatever was in memory where ptr was declared.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0

You can't deterrence a pointer that doesn't point to somewhere you own.

int* ptr;

That allocates space for the pointer, but it doesn't allocate space for the chunk the pointer points to.

Also, since it's not initialized, ptr has an indeterminate value. This means that not only does it likely point to something you don't own, it also would be rather difficult to check if it's a valid pointer. It's usually a good idea to initialize pointers to either NULL (or nullptr if available) or an actual location (like you did in the first example).

Corbin
  • 33,060
  • 6
  • 68
  • 78