typedef of pointer to array of char

In Stroustrup's "The C++ Programming Language", exercise 3 of 5.9, I'm to "Use typedef to define the type pointer to array of char".

I've tried:

 
typedef char (*PtrCharArrayOf3)[3];


and

1
2
typedef char CharArrayOf3[3];
typedef CharArrayOf3 *PtrCharArrayOf3;


but when I try to use this:

1
2
char a[3] = "ab";
PtrCharArrayOf3 parray = a;


I get:

error C2440: 'initializing' : cannot convert from 'char [3]' to 'PtrCharArrayOf3'

I'm missing something fundamental here.

I read

 
typedef char *mychArr[]; //pointer to array of char 


at http://www.daniweb.com/forums/thread62686.html# as a solution, but I don't see either how this works or how to use it when defining a variable.

Thoughts?

Consider what you already know:
1
2
3
4
5
6
7
8
int i;
int* ptr;

// i is an int
// ptr is a pointer to int
// therefore to get a pointer to i, you use &:

ptr = &i;


And apply it the same way:

1
2
3
4
5
6
7
8
9
typedef char (*PtrCharArrayOf3)[3];

char a[3] = "ab";
PtrCharArrayOf3 ptr;

// 'a' is a char[3]
// 'ptr' is a ptr to a char[3]

ptr = &a;



The thing that makes this tricky is that array names can be implicitly cast to pointers:

1
2
3
4
5
6
7
char a[3] = "ab";
PtrCharArrayOf3 ptr3;
char* ptr;

ptr3 = &a;  // points to the array
ptr = a;  // points to the first char in the array
//  effectively they point to the same thing, but via different types, and with different syntax 



HOWEVER -- all that said -- the necessity of these types of pointers is rare to the point of being virtually nonexistant. If you find yourself needing to do this in a program, I'd recommend you question your approach, as there's probably a cleaner, simpler, and less funky solution to the problem at hand.
Thank you so much! That made it perfectly clear.
Topic archived. No new replies allowed.