C++ difference in sending an array as a value/pointer -


so somehow got work, interested why first attempt failed.

i have informal experience c, , trying learn c++. thought experiment few common commands, such passing arguments function, recieved "incomplete type error" when trying acess contents of passed array.

this erroneous code:

    void printoutarray(int array[][], int height, int width){         (int x = 0; x < width; x++){             (int y = 0; y < height; y++){                 cout << array[x][y]) << " ";             }             cout<<"\n";         }     } 

i able fix code using pointers:

    void printoutarray(int *array, int height, int width){         (int x = 0; x < width; x++){             (int y = 0; y < height; y++){                 cout << *(array+x*width+y) << " ";             }             cout<<"\n";         }     } 

and passing array this:

    #define hght 5     #define wdth 5     /*other code/main function*/     int inputarray[hght][wdth] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};     printoutarray(*inputarray, hght, wdth); 

but question why have send function pointer of array. shouldn't array variable pointer itself? also, why did need include dereference operator in "fixed" code, because sending pointer of pointer? again i'm curious workings of language, insight appreciated, thanks!

arrays converted pointers when passed function (true in c , c++). mistake seems thinking because of 2d array should converted double pointer when passed function, isn't true.

you have 2d array

int inputarray[hght][wdth] = ...; 

one way of looking @ it's array of size hght, each element of array array of size wdth. when converting array pointer, pointer array of size wdth. this

void printoutarray(int array[][wdth], int height, int width){ 

or more explicitly this

void printoutarray(int (*array)[wdth], int height, int width){ 

with either of these slight changes original code work. though in both cases width parameter useless, because function works on arrays width wdth

nothing happening here wouldn't work same way in c.


Comments