1

I wondered what is the big difference between setting up C pointers in this way:

int int_var = 5;
int *int_ptr = &int_var;

And this way:

int int_var = 5;
int *int_ptr = int_var;

Since in both cases the result of *int_ptr will be 5, no?

rel-s
  • 6,108
  • 11
  • 38
  • 50
  • 3
    *in both cases the result of *int_ptr will be 5, no?* No. – cnicutar Apr 09 '13 at 19:12
  • 2
    In the second case, `*int_ptr` will be whatever is stored at memory address 5. In other words, garbage. – jpm Apr 09 '13 at 19:13
  • 1
    Hint: turn up the warning level on your compiler and/or pay attention to the warning you're already getting ;). – FatalError Apr 09 '13 at 19:14
  • Do you use `gcc`? Then activate all warnings: `-Wall -Wextra -pedantic`. This should already tell you that there is something smelly going on. – Zeta Apr 09 '13 at 19:14
  • @jpm It's more likely the OS will catch it as an invalid access since such low addresses are rarely mapped. – cnicutar Apr 09 '13 at 19:14
  • @cnicutar In a sane run time, probably, but it's not guaranteed, so a crash (probably segfault) will be the best case scenario upon a dereference. – jpm Apr 09 '13 at 19:17

4 Answers4

2

No, only in the first case. The second case will cause undefined behavior when you'll try to deference the pointer. Use the first case.

Some explanation:

int int_var = 5;
int *int_ptr = &int_var; // here int_ptr will hold the address of var

Whereas

int int_var = 5;
int *int_ptr = int_var; // here int_ptr will hold the address 5.
Avidan Borisov
  • 3,235
  • 4
  • 24
  • 27
0

No. In first case 5, in second case is undefined, is the conten of the memmory with adress 5. ??

qPCR4vir
  • 3,521
  • 1
  • 22
  • 32
0

No the int_ptr is a pointer so you have to assign an address to it when you define it

The first is the right one

int int_var = 5;
int *int_ptr = &int_var;

the other is wrong

the other one you are assigning an int value 5 to the pointer int_ptr (address) so it's like you assign 5 as address for the pointer int_ptr

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

In C, pointers point to the address itself. The address-of & operator is where the address of the variable is.

So in:

int int_var = 5;
int *int_ptr = &int_var;

*int_ptr would correctly be used since it is pointed to the ADDRESS of int_var which has the value of 5

However in:

int int_var = 5;
int *int_ptr = int_var;

*int_ptr points to an address that is 5, NOT the address where value 5 is located, which would be some random number.

In addition about arrays:

char *y;
char x[100];
y = x;

This can be done since an array is actually an address.

For more information.

user207421
  • 305,947
  • 44
  • 307
  • 483
herinkc
  • 381
  • 2
  • 13