Pointer to multidimensional array

S

shane

Ive searched a fair bit for the answer, but nothing has come up that
matches what i want to do. I'm having an issue with passing and
assigning pointers to multidimensional arrays.

The code:

/*.....*/
TCHAR msg[2][4][MAX_PATH]
func(msg);
/*.....*/

func(TCHAR *pmsg[2][4][MAX_PATH])
{
TCHAR *m_pmesg;
m_pmesg = pmsg;
}

Ive tried a few different variations but with no luck. I keep getting
the error

error C2440: '=' : cannot convert from 'TCHAR *[][2][260]' to 'TCHAR
*[4][2][260]'

on the line 'm_pmesg = pmsg' as well as 'func(msg)'.
I would appreciate any help.
 
G

Gianni Mariani

shane said:
Ive searched a fair bit for the answer, but nothing has come up that
matches what i want to do. I'm having an issue with passing and
assigning pointers to multidimensional arrays.

The code:

/*.....*/
TCHAR msg[2][4][MAX_PATH]
func(msg);
/*.....*/

func(TCHAR *pmsg[2][4][MAX_PATH])

You ca do either:

func(TCHAR pmsg[2][4][MAX_PATH])

or
func(TCHAR pmsg[][4][MAX_PATH])

or

func(TCHAR (&pmsg)[2][4][MAX_PATH])

{
TCHAR *m_pmesg;
m_pmesg = pmsg;
}

Ive tried a few different variations but with no luck. I keep getting
the error

error C2440: '=' : cannot convert from 'TCHAR *[][2][260]' to 'TCHAR
*[4][2][260]'


This is because an array becomes a pointer when it is passed to a
function (unless it's passed by reference). Arrays are never passed by
value (unless they are in a struct or class).

e.g.

void func( char i[] ); // (essentially the same as func( char * i ) )
char v[30];

func( v );

However, if you want to maintain all array information, you can pass by
reference.

void func( char (&i)[30] );
func( v );

on the line 'm_pmesg = pmsg' as well as 'func(msg)'.

m_pmesg is a pointer to a element of the array but you're trying to
assign it a pointer to the entire array. Hence you get the message of
type mismatch.

const int MAX_PATH = 200;

char msg[2][4][MAX_PATH];


void func(char pmsg[2][4][MAX_PATH])
{
char * m_pmesg;
m_pmesg = pmsg[0][0];
}

int main()
{
func( msg );
}
 
S

shane

Thanks for your help, though I did actually fix it not long after
posting :)

I used the below code, note the '(*)'. All I needed was some
paranthese around the *, though I don't really understand why to be
honest.

I also needed a '&' when passing the array for some reason. As you
said, arrays are always passed by reference so Im not sure why thats
needed.


/*.....*/
TCHAR msg[2][4][MAX_PATH]
func(&msg);
/*.....*/

func(TCHAR (*)pmsg[2][4][MAX_PATH])
{
m_pmsg = pmsg;
printf(*m_pmsg[1][2]);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top