On 20/06/2019 12:22, Bart wrote:
> On 20/06/2019 05:51, G G wrote:
>> i saw this on the internet
>> could you please explain?
>>
>> int anArray[] = { 6, 7, 8, 9 }Â --- array initialized
>> Â such that: anArray[0] = 6
>> Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â anArray[1] = 7
>> Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â anArray[2] = 8
>> Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â anArray[3] = 9
>>
>> int *ptr --- is a pointer to int
It is common in C++, but by no means universal, to write this as
int* ptr;
This reads as "ptr is a pointer-to-int".
In C, it is common but far from universal to write:
int *ptr;
Reading as "*ptr is an int".
C++ emphasises the type, C emphasises the use of the identifier.
>>
>> int *(ptr[4])Â ---- is an array of pointers to int ?
>>
>> int *ptr[4] ---- ? (same as above ?)
If you write this as:
int* ptr[4];
it becomes clearer.
>>
>> int ( *ptr[]) (void) --- ouch?
>>
>
C declarations are based on their usage. So this means that "ptr[100]"
would be a pointer to a function that takes no parameters (void), and
returns int. So "ptr" is an array of such pointer functions.
You can't have "int ( *ptr[]) (void);" on its own, just as you can't
define "int x[];" on its own, as the compiler doesn't know the number of
elements. You have to have a size for the array, or an "extern".
> 'Ouch' as in 'what the hell does this mean', or 'what do you use it for'?
>
> If the former, then you might try:
https://cdecl.org, which turns such
> declarations into English, or vice versa.
>
> However - 'ptr' appears to mean something special there, and generates a
> syntax error. So try a different name, like 'p'.
Just to be clear - this is an artefact of the
cdecl.org website. "ptr"
has no special meaning in C or C++.
If you find
cdecl.org a useful tool, great. Personally, I much prefer
to use typedefs to make complex types clearer. Obviously you can only
do that when you write code - when reading other people's code, you have
to understand what /they/ write.
So if this array was for a collection of prime number generator
functions, I'd use:
typedef int (*FPrimeGenerator)(void);
extern FPrimeGenerator generatorFunctions[];