Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between int* ptr and int *ptr in C? [duplicate]

I am fairly new at C and I don't know the difference between the following two variable declarations:

int* ptr;
int *ptr;

I think that in the declaration int* ptr;, ptr's value cannot be changed whereas it can be changed for the declaration, int *ptr;

I am not sure if that is it though.

What is the concept behind the two declarations?

like image 300
anpatel Avatar asked Oct 17 '11 21:10

anpatel


People also ask

What is the difference between * ptr and ptr in C?

When you do: int* ptr; You are declaring a pointer of type integer named ptr. When you do: *ptr; You tell the program to point to the address stored in ptr.

What is the difference between * ptr and &ptr?

*ptr is the pointer to your variable. &ptr gives you the address of ptr, so a pointer to the pointer to the pointer to your variable.

What is the difference between * p and p * in C?

*p is dereferencing a pointer, p* is multiplying the pointer by something.

What is the meaning of int (* ptr )[ 5?

Answer: (E) Explanation: Here p is basically a pointer to integer array of 5 integers. In case of “int *p[5]”, p is array of 5 pointers to integers.


3 Answers

To the compiler, there is no difference between the two declarations.

To the human reader, the former may imply that the "int*" type applies to all declarations in the same statement. However, the * binds only to the following identifier.

For example, both of the following statements declare only one pointer.

int* ptr, foo, bar;
int *ptr, foo, bar;

This statement declares multiple pointers, which prevents using the "int*" spacing.

int *ptr1, *ptr2, *ptr3;
like image 133
Andy Thomas Avatar answered Nov 14 '22 02:11

Andy Thomas


Spaces in C are mostly insignificant. There are occasional cases where spaces are important, but these are few and far between. The two examples you posted are equivalent.

like image 22
Ted Hopp Avatar answered Nov 14 '22 00:11

Ted Hopp


Like the others said. There is no difference. If you want to understand more complex C type declaration you could find this link userful. Reading C declarations.

like image 2
Xyand Avatar answered Nov 14 '22 02:11

Xyand