Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placement of the asterisk in pointer declarations

I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition.

How about these examples:

  1. int* test;
  2. int *test;
  3. int * test;
  4. int* test,test2;
  5. int *test,test2;
  6. int * test,test2;

Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one.

The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?

like image 964
Michael Stum Avatar asked Oct 07 '08 21:10

Michael Stum


People also ask

Where should the asterisk go in a pointer?

When declaring a pointer type, place the asterisk next to the type name. Although you generally should not declare multiple variables on a single line, if you do, the asterisk has to be included with each variable.

Which is the correct way of declaring a pointer?

The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double) too. Naming Convention of Pointers: Include a "p" or "ptr" as prefix or suffix, e.g., iPtr, numberPtr, pNumber, pStudent.

What does * indicate in pointer?

In an expression, *pointer refers to some object using its memory address. A declaration such as int *pointer means that *pointer will refer to an int . Since *pointer refers to an int , this means that pointer is a pointer to an int .

What does * indicate in pointer in C?

A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.


1 Answers

4, 5, and 6 are the same thing, only test is a pointer. If you want two pointers, you should use:

int *test, *test2; 

Or, even better (to make everything clear):

int* test; int* test2; 
like image 149
Milan Babuškov Avatar answered Sep 22 '22 05:09

Milan Babuškov