Friday 15 March 2013

passing multidimensional array as argument in C -



passing multidimensional array as argument in C -

c newbie here, need help: can explain (and offer workaroud) me why works:

int n=1024; int32_t data[n]; void synthesize_signal(int32_t *data) { ...//do data}

which allow me alter info in function; not?

int n=1024; int number=1024*16; int32_t data[n][2][number]; void synthesize_signal(int32_t *data) { ...//do data}

the compiler error message expected int32_t * got int32_t (*)[2][(sizetype)(number)] instead.

first, passing arrays in c reference. pass pointer of sort, , function can modify info in array. don't have worry passing pointer array. in fact, in c there no real different between pointer happens to beingness of array, , array itself.

in first version. making one-dimensional array data[n], , passing function. in array, you'll using saying, data[i]. translates straight (data + (i sizeof(int32_t)). using size of elements in array find memory location positions in front end of origin of array.

int n=1024; int number=1024*16; int32_t data[n][2][number]; void synthesize_signal(int32_t *data)

in sec case, you're setting mufti-dimensional array (3d in case). setup correctly. problem when pass function, thing gets passed address of beingness of array. when gets used within function, you'll like

data[i][1][x] = 5;

internally c calculating how origin of array location is. in order that, need know dimensions of array. (unlike newer languages, c store info array lengths or sizes or anything). need alter function signature knows shape/size of array expect. because of way, calculates array positions, doesn't need first dimension.

in case, alter function signature this:

void synthesize_signal(int32_t data[][2][number]) { ...

setup array same way doing sec 1 above, , phone call you'd expect:

synthesize_signal(data);

this should prepare you.

the comments mention useful info using more descriptive variable names, , global vs. local variable. valid comments maintain in mind. addressed code problem you're having in terms of mufti-dimensional arrays.

c arrays pointers multidimensional-array

No comments:

Post a Comment