简体   繁体   中英

C function pointer confusion, what is meant by “pointer level of the variable”?

This is the code:

char *(*strcpy_ptr)(char *dst, const char *src); Pointer to strcpy-like function

And the tutorial says:

Note the parentheses around *strcpy_ptr in the above declaration. These separate the asterisk indicating return type (char *) from the asterisk indicating the pointer level of the variable (*strcpy_ptr — one level, pointer to function).

I'm lost on this - where is the "function pointer" and what is the "pointer level" ?

You are declaring a variable strcpy_ptr . You want this variable to be a pointer to a function returning a char* . If you did it without the parentheses this way:

char **strcpy_ptr(char *dst, const char *src);

It would be the prototype of a function that returns a char** - not what you want. The parentheses are to group one star with the variable , and seperate the star from the return type .

Remember that pointers are declared like this:

T *var;

Where T is some type. The more stars you add, the more levels of indirection you add before you finally get to the actual T . So char **c would be a pointer to a pointer to a char . It's the same thing for function pointers: T is char* , and *var must be seperated by parentheses, because C is ignorant of white space. C just added a little extra syntax to specify what kind of and how many arguments the function takes that is pointed to by the pointer. This is just part of the way C works.

Without the parens, you would have: **strcpy_ptr

This is a pointer to a pointer or double indirection. I think 'one level' means there is just one level of indirection.

@Adel: all most all parts of the above comments make some sense (with few picky exceptions like C doesn't understand white space), still I will suggest you to read "C programming language" by Kernighan and Ritchie, 2nd edition, chapter 5.11 and specially chapter 5.12 (Complicated expressions-p122): you will find good number of complicated examples and it is important to understand each one of them.

specially, understanding the differences between:

  1. char (* (* x()) [] ) ()

and

2.char (*(*x[])())[]

cforfun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM