Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

pointers

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 *?

like image 628
Pieter Avatar asked Jan 19 '10 15:01

Pieter


People also ask

What is the difference between asterisk and ampersand in C?

The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable. It is known as value of operator.

What is the role of & and * operator in pointer?

Answer: * Operator is used as pointer to a variable. Example: * a where * is pointer to the variable a. & operator is used to get the address of the variable.

What does * and & indicate in pointer?

The fundamental rules of pointer operators are: The * operator turns a value of type pointer to T into a variable of type T . The & operator turns a variable of type T into a value of type pointer to T .

What is the ampersand for in pointers?

This & symbol is called an ampersand. This & is used in a unary operator. The purpose of this address operator or pointer is used to return the address of the variable.


1 Answers

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 
like image 57
Dan Olson Avatar answered Sep 25 '22 15:09

Dan Olson