Thursday, 26 May 2016

Pointers in C: when to use the ampersand and the asterisk?



I'm just starting out with pointers, and I'm slightly confused. I know & means the address of a variable and that * can be used in front of a pointer variable to get the value of the object that is pointed to by the pointer. But things work differently when you're working with arrays, strings or when you're calling functions with a pointer copy of a variable. It's difficult to see a pattern of logic inside all of this.



When should I use & and *?



Answer



You have pointers and values:



int* p; // variable p is pointer to integer type
int i; // integer value


You turn a pointer into a value with *:



int i2 = *p; // integer i2 is assigned with integer value that pointer p is pointing to



You turn a value into a pointer with &:



int* p2 = &i; // pointer p2 will point to the address of integer i


Edit:
In the case of arrays, they are treated very much like pointers. If you think of them as pointers, you'll be using * to get at the values inside of them as explained above, but there is also another, more common way using the [] operator:




int a[2];  // array of integers
int i = *a; // the value of the first element of a
int i2 = a[0]; // another way to get the first element


To get the second element:



int a[2]; // array
int i = *(a + 1); // the value of the second element
int i2 = a[1]; // the value of the second element



So the [] indexing operator is a special form of the * operator, and it works like this:



a[i] == *(a + i);  // these two statements are the same thing

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...