A friend of mine was trying to test me on C (my strongest language is C++) and he asked me three questions which I could not answer:
Try to explain the following declarations:
1) int (*x)(int, char *, void *);
2) int (*x[10])(int, char *, void *);
3) int (**x[10])(int, char *, void *);
Can anyone explain these function declarations and explain what concepts are being used?
Let's take a look at how pointers are used in the C programming Language. We are going to deal with two variables: a ptr. We are also going to meet two key characters: & - where &a would return the address location of variable a * - where *ptr = 8 means follow the memory address stored in ptr and set that location to 8.
Assignment Operators Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions. For z/OS® XL C/C++, use the __cdecl keyword to declare a pointer to a function as a C linkage.
A normal array stores values of variables, and pointer array stores the address of variables. Capacity. Usually, arrays can store the number of elements the same size as the size of the array variable. A pointer variable can store the address of only one variable at a time.
You need the cdecl
program, which will give you a definite, correct answer to such questions. Learning to interpret such statements manually is doable and beneficial, but even so cdecl is extremely useful for checking if you have an correct answer.
prompt>cdecl
Type `help' or `?' for help
cdecl> explain int (*x)(int, char *, void *);
declare x as pointer to function (int, pointer to char, pointer to void) returning int
cdecl> explain int (*x[10])(int, char *, void *);
declare x as array 10 of pointer to function (int, pointer to char, pointer to void) returning int
cdecl> explain int (**x[10])(int, char *, void *);
declare x as array 10 of pointer to pointer to function (int, pointer to char, pointer to void) returning int
cdecl>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With