What is the difference between int* p, int *p and int * p?
Quick answer, NO difference.
They all perform the same functionality, only different in format.
Examples
1 | // These are 3 types of declaration of pointers, functional the same only differ in format. |
Method 1 and 2 are the most common way to declare a pointer.
Method 1 is clearest because it puts all data types together (int, pointer) so readers know p1 is a pointer to an int.
Method 2 is more convenient when declaring multiple variables in one line.
1 | int *p1, *p2; |
Be aware when declaring multiple pointers in one line, remember to add
*
in front of each variable name, otherwise, you will encounter errors below.
1 | int num = 5; |
Output
1 | sizeof(int): 4 |
Output indicating the size of p2 is equal to an int which means p2 is not a pointer instead it is an int.
After fix
1 | int num = 5; |
Output
1 | sizeof(int): 4 |
Now the size of p1 and p2 are both equal to the size of a pointer which means p1 and p2 are two pointers.
Conclusion
When declaring a pointer, it is always best practice to declare it in method 1 or 2.
1 | int* p; |
Method 1 is the clearest type of declaration, it puts all data types together so readers can understand this variable is a pointer instantly. But, it was not good when declaring multiple variables in one line.
1 | int *p1, *p2, *p3; |
Method 2 is more suitable when trying to declare multiple variables in one line.
References
About this Post
This post is written by Andy, licensed under CC BY-NC 4.0.