Thursday, 15 March 2018

c++ - Are there other ways of passing array in a function?










My question is related to passing an array as a C++ function argument. Let me show the example first:



void fun(double (*projective)[3])

{
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
{
projective[i][j]= i*100+j;
}
}

int main()
{

double projective[3][3];

fun(projective);
for(int i=0; i<3; i++)
{
cout< for(int j=0; j<3; j++)
cout< }



return 0;
}


In the example, the passing argument for fun is an array, and I was wondering whether there are other ways of passing this argument. Thanks!


Answer



fun takes a pointer-to-array-of-3-double and it assumes (relying on the caller) that this points to the first element of an array of at least 3 arrays-of-3-doubles. Which it does, because as you say the argument supplied to the call in main is an array. This immediately decays to a pointer to its first element.



One alternative would be for fun to take a pointer-to-3x3-array-of-double, since it assumes that size anyway and the caller does in fact have such a beast:




void fun(double (*p_projective)[3][3])
{
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
{
(*p_projective)[i][j]= i*100+j;
}
}



Call it with fun(&projective).


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...