Wednesday, 15 August 2012

c - Writing to a 2D Array via Pointer Notation -



c - Writing to a 2D Array via Pointer Notation -

i'm having problem understanding why incrementing pointers in pnarrycpy below incorrect. figured out how re-create array using pointer notation different way, need understand what's wrong (e.g., (* tgt_s)++; int (*tgt_s)[cs]), , why tgt_s lvalue (e.g., tgt_s++ valid) *tgt_s is not (really) lvalue.

int main(void) { int arr1[2][4] = { {1, 2, 3, 4}, {6, 7, 8, 9} }; int arr2[2][4]; pnarrcpy(4, arr1, arr2, arr2+2); // copies 2d array using pointer notation // - problem is. printarr(2, 4, arr2); // prints array , works fine - not @ issue putchar('\n'); homecoming 0; } void pnarrcpy(int cs, int (*src)[cs], int (*tgt_s)[cs], int (*tgt_e)[cs]) { while (tgt_s < tgt_e) { **tgt_s=**src; (* tgt_s)++; // older versions of gcc warn "target of assignment not // lvalue", latest versions throw error (* src)++; // no errors runtime } return; } // trucated rest of programme since it's not relevant, function printing // array

under older gcc, programme compiles , displays right results, namely:

1 2 3 4 6 7 8 9

mac os 10.8.2 gcc 4.7.2 gave me error gcc 4.2.1 giving me warnings

thank you!!

edit: reason i'm using variable length arrays: function part of program, , 1 driver using troubleshoot pnarrcpy. in actual program, array dimensions , contents user defined, hence utilize of vla.

the thing is:

int (*tgt_s)[cs] pointer array. take few seconds think that, it's bit of exotic pointer *tgt_s hence array arrays not modifiable lvalues

what makes hardest understand way you're using c99 feature of passing cs , using in parameter list.

if want larn more vlas function arguments, check out this first-class post.

c arrays pointers gcc lvalue

No comments:

Post a Comment