What does
int *(cmp)(char*, char*);
mean?What is the difference between
char* ptr1;
andchar *ptr2;
Asked
Active
Viewed 68 times
0

Vlad from Moscow
- 301,070
- 26
- 186
- 335

Newbie
- 95
- 9
-
11) [see here](https://cdecl.org/?q=int+*%28cmp%29%28char*%2C+char*%29%3B) 2) just writing style. – Blaze Mar 09 '20 at 09:56
-
11. `int *(cmp)(char*, char*);` is simply `int *cmp(char*, char*);`: `cmp` is a function that takes two arguments and both of type `char *` and returns a pointer to `int`. 2. No difference. It's matter of choice. – haccks Mar 09 '20 at 10:02
-
1In the second I prefer `char *ptr2;` because in `char* ptr2, ptr3;` the `ptr3` is not a pointer, it is `char ptr3;` – Weather Vane Mar 09 '20 at 10:10
-
3Since it's called `cmp` (compare?), I'd be inclined to think the signature is actually `int (*cmp)(char*, char*);`, i.e. a pointer to a function which returns an `int`, as a parameter for a `qsort`-style *comparison* function (as [explained here](https://cdecl.org/?q=int+%28*cmp%29%28char*%2C+char*%29%3B)). [This thread](https://stackoverflow.com/q/27284185/69809) might be useful if you want to see how to write such a function. – vgru Mar 09 '20 at 10:30
-
1@WeatherVane Simply don't write multiple declarations on a single line - doing so is a well-known safety hazard. Not just for pointers; I've also seen things like `int a,b,c = 0;` when the programmer meant to set all items to zero, not just `c`. – Lundin Mar 09 '20 at 10:36
-
1@Groo Good remark, though in that case it should have been `int (*cmp)(const void*, const void*)`. – Lundin Mar 09 '20 at 10:37
1 Answers
2
this
int *(cmp)(char*, char*);
is a declaration of a function that has the return type int *
and two parameters of the type char *
.
You may enclose a declarator in parentheses. So the above function declaration can be also rewritten like
int * ( (cmp)(char*, char*) );
The both declarations are equivalent to
int * cmp(char*, char*);
A declaration of a pointer to such a function will look like
int * ( *p_cmp )(char*, char*) = cmp;
There is no difference between these declarations
char* ptr1;
char *ptr1;
char * ptr1;

Vlad from Moscow
- 301,070
- 26
- 186
- 335