I have some difficulties grasping some concepts. Grateful for help.
Let's say you have the following piece of code:
int *intPtr; // creates a pointer
int count = 10; // initiates an intiger variable
intptr = &count; // ??
The &
operator gives the address to a variable, in this case the integer count
. The address is then assigned to the intptr
. My question is: Why is intptr = count;
not sufficient. I know that count
is a variable and intptr
is a pointer, but isn´t a variable also just referring to some place in memory?
Hans
count refers to the VALUE of the variable. You don't want to assign the value of count to intptr, you want to assign the address of count. Thus the & operator is used.
If you do intptr = count, you'd be pointing to memory address 10 in this case, which is sure to be in system memory, not your application memory and you'd crash.
It is important to understand that pointers have actually a different data type.
A int
variable will hold integer values.
A pointer
variable will hold memory addresses.
So it is not right to assign an int variable to a pointer variable (as you suggested intptr = count;
)
I believe using a typedef
could help you better understand the difference.
Here's a small example:
#include <stdio.h>
typedef int* int_pointer;
int main() {
int n; // integer
int_pointer p; // pointer
n = 5;
p = &n; // p's value is now n's address
*p = *p + 1; // add 1 to the value stored at the location that p points to
// and put that value back in the same location
printf("n = %d\n", n);
printf("*p = %d\n", *p);
return 0;
}
This program will print
n = 6
*p = 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With