Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding C++ pointer syntax

I'm not able to understand this statement of code that I came across during my interview.

int(*(*ptr[3])(char*))[2];

I've tried looking at an IDE but all I have is that it is an array of data type

int (*(*[3])(char *)) 

I wasn't able to understand this.

like image 229
asreerama Avatar asked Aug 22 '19 05:08

asreerama


People also ask

Why are pointers sometimes difficult to understand?

Pointers are not very difficult it is indeed confusing than difficult. I find it confusing due to it's syntax and different crossovers like arrar/pointers crossovers in this case it is difficult to keep track. Second thing which make pointers confusing is that pointers hold no information about what they point to.

What is the syntax of pointer in C?

Pointer Syntax Here is how we can declare pointers. int* p; Here, we have declared a pointer p of int type. You can also declare pointers in these ways.

Are pointers in C++ difficult?

Pointer is also the most complex and difficult feature in C/C++ language. If we use pointers correctly, pointers can widely improve efficiency and performance. In other words, if we use them erroneously, they cause many problems, such as un-readable and un-maintainable codes or memory leaks and buffer overflow.

What are the two common problems with pointers?

# What are the two common problems with pointers? Dangling pointers (dangerous) and Lost heap-dynamic variable.


1 Answers

May be you could just break it down one at a time to understand the syntax better. First start up with a simple definition without the array notation

int(*(*ptr)(char*));

So ptr is a function pointer that takes a char pointer as an argument and returns a pointer to an int. Now extending it to the array notation

int(*(*ptr[3])(char*))[2];

which means you have an array of function pointers, each of which will take a char pointer argument and return a pointer to an array of two integers.

You can see this working if you have a make a function call using these pointers you define. Note that, the below functions are for demonstrative purposes only and do not convey any logical purpose

#include <iostream>

static int arr[2] = { 2, 2 };

// initialize  'bar' as a function that accepts char* and returns
// int(*)[2]
int (*bar(char * str))[2] {
    return &arr;
}

int main() {
    // pointer definition, not initialized yet
    int(*(*foo[3])(char*))[2];
    char ch = 'f';
    // as long as the signatures for the function pointer and 
    // bar matches, the assignment below shouldn't be a problem
    foo[0] = bar;
    // invoking the function by de-referencing the pointer at foo[0]
    // Use 'auto' for C++11 or declare ptr as int (*ptr)[2] 
    auto *ptr = (*foo[0])(&ch);
    return 0;
}
like image 67
Inian Avatar answered Sep 22 '22 12:09

Inian