February 4, 2024

int* p int *p int * p Pointer in C

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
2
3
4
// These are 3 types of declaration of pointers, functional the same only differ in format.
int* p1; // Method 1
int *p2; // Method 2
int * p3; // Method 3

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
2
3
4
5
6
7
8
9
10
11
12
int num = 5;

int *p1, p2;

p1 = #
p2 = #

printf("sizeof(int): %d\n", sizeof(int));
printf("sizeof(int*): %d\n", sizeof(int*));

printf("sizeof(p1): %d\n", sizeof(p1));
printf("sizeof(p2): %d\n", sizeof(p2));

Output

1
2
3
4
sizeof(int): 4
sizeof(int*): 8
sizeof(p1): 8
sizeof(p2): 4

Output indicating the size of p2 is equal to an int which means p2 is not a pointer instead it is an int.

截屏2024-02-04 下午2.38.57


After fix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int num = 5;

int *p1, *p2;

p1 = #
p2 = #

printf("sizeof(int): %d\n", sizeof(int));
printf("sizeof(int*): %d\n", sizeof(int*));

printf("sizeof(p1): %d\n", sizeof(p1));
printf("sizeof(p2): %d\n", sizeof(p2));

printf("*p1: %d\n", *p1);
printf("*p2: %d\n", *p2);

Output

1
2
3
4
5
6
sizeof(int): 4
sizeof(int*): 8
sizeof(p1): 8
sizeof(p2): 8
*p1: 5
*p2: 5

Now the size of p1 and p2 are both equal to the size of a pointer which means p1 and p2 are two pointers.

截屏2024-02-04 下午2.39.10

截屏2024-02-04 下午2.44.09


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.

#C#Pointer