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?
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?
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.
No. In first case 5, in second case is undefined, is the conten of the memmory with adress 5. ??
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
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.