Pointers and Reference!

1. Declares cHelp to be “a function returning a reference to a char” that has a parameter named help that’s “a reference to a float”.

2. Declares abc to be “a pointer to an array of 6 pointers to shorts”.

3. Declares def to be “a reference to a pointer to an array of 6 pointers to shorts”.

4. Declares dpA to be “an array of 6 pointers to doubles”.

5. Type casts (C-style) dpA to “a pointer to an array of 6 pointers to shorts” and assigns the result to abc.

I am struggling to write No.3 and 5. Getting Syntax Errors.

Can you guys help me what I am doing wrong??


1
2
3
4
5
    char &cHelp(float &help); //No.1
    short *(*abc)[6]; //No.2
    short *(*&def)[6]; //No.3
    double *dpA[6]; //No.4
    abc = (short *(*)[6]); //No.5 
Last edited on
According to https://en.cppreference.com/w/cpp/language/explicit_cast
a C style cast expression has syntax:
( new_type ) expression

On 5, the expression is dpA. Furhermore, you assign to abc:
abc = ( new_type ) dpA ;
What remains, is to write the correct new_type.


The 3 declares a reference. You can't declare a reference without initializing it. You should probably create def as reference to abc (from case 2), for that has correct type?
Last edited on
Can you elaborate more?

I am kind of confused and not able to understand it.

Thanks
Lets ask a compiler
1
2
3
4
5
6
7
8
// my first program in C++
int main()
{
  short *(*&def)[6]; // #3, error
  int x;
  int& y; // error
  int& z = x; // ok
}

 In function 'int main()':
4:19: error: 'def' declared as reference but not initialized
6:8: error: 'y' declared as reference but not initialized

See? You must initialize a reference.

1
2
3
4
5
6
7
// my second program in C++
int main()
{
  short *(*abc)[6]; // #2
  auto& def = abc;  // #3
  def = 'a';  // intentional error
}

 In function 'int main()':
6:7: error: invalid conversion from 'char' to 'short int* (*)[6]' [-fpermissive]

The 'def' is a reference, it is initialized to refer to 'abc', and it has a type short int* (*)[6] too.

1
2
3
4
5
6
7
// my third program in C++
int main()
{
  short *(*abc)[6]; // #2
  short *(*&def)[6] = abc; // #3
  def = 'a'; // intentional error
}

 In function 'int main()':
6:7: error: invalid conversion from 'char' to 'short int* (*)[6]' [-fpermissive]

Would you say that second and third program behave similarly?
Thanks for explaining it to, got the idea behind it.

I am still getting this error near No.5, I don't know why?

Can you tell me where I am doing wrong?

1
2
3
4
5
6
7
8
9
10
#include <iostream>

void TestDeclarations()
{
    char &cHelp(float &help); //No.1
    short *(*abc)[6]; //No.2
    short *(*&def)[6] = abc; // 3.
    double *dpA[6]; // 4.
    abc = (short *(*)[6]); //No.5
}
Last edited on
5. Type casts (C-style) dpA


dpA? in abc = (short *(*)[6]);?
Topic archived. No new replies allowed.