Reducing Repeated code for arrays

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • JellyBum

    Reducing Repeated code for arrays

    Hey there, having a bit of a problem trying to acheive something..

    Ive got 2 arrays, ArrayA, ArrayB both are of type char with [5][7]
    dimensions.

    Ive got code in a function, which does
    if(ArrayA[x][y] == 'A') { // do something }

    but i also have
    if(ArrayB[x][y] == 'A') { // do something }

    so for each array im doubling it.

    Im wondering, if i could do, if(SOMETHING[x][y] ==

    and then reference the arrayname in SOMETHING

    Any ideas please?

    Thanks


  • Rob van der Leek

    #2
    Re: Reducing Repeated code for arrays

    In article <J4qlc.26$XC3.1 5@newsfe6-win>, JellyBum wrote:[color=blue]
    > Ive got 2 arrays, ArrayA, ArrayB both are of type char with [5][7]
    > dimensions.
    >
    > Im wondering, if i could do, if(SOMETHING[x][y] ==
    > and then reference the arrayname in SOMETHING[/color]

    You can access both arrays via a pointer. Your pointer must have the
    type:
    char (*pArray)[7]

    if you want to be able to point it to arrays of type:

    char ArrayA[5][7]

    then you can say:

    pArray = ArrayA; // or: pArray = ArrayB
    if (pArray[x][y] == ...

    Regards,
    --
    Rob van der Leek | rob(at)ricardis (dot)tudelft(do t)nl
    Ricardishof 73-A | http://www.ricardis.tudelft.nl/~rob
    2614 JE Delft, The Netherlands
    +31 (0)6 155 244 60

    Comment

    • Mike Wahler

      #3
      Re: Reducing Repeated code for arrays


      "JellyBum" <......@......c om> wrote in message
      news:J4qlc.26$X C3.15@newsfe6-win...[color=blue]
      > Hey there, having a bit of a problem trying to acheive something..
      >
      > Ive got 2 arrays, ArrayA, ArrayB both are of type char with [5][7]
      > dimensions.
      >
      > Ive got code in a function, which does
      > if(ArrayA[x][y] == 'A') { // do something }
      >
      > but i also have
      > if(ArrayB[x][y] == 'A') { // do something }
      >
      > so for each array im doubling it.
      >
      > Im wondering, if i could do, if(SOMETHING[x][y] ==
      >
      > and then reference the arrayname in SOMETHING
      >
      > Any ideas please?[/color]

      Use a function.

      #include <stdio.h>
      #include <stdlib.h>

      void foo(char (*arr)[7])
      {
      size_t row = 0;
      size_t col = 0;
      char value = 'A';

      printf("[%ld][%ld]", (unsigned long)row, (unsigned long)col);

      if(arr[0][0] == value)
      printf(" == ");
      else
      printf(" != ");

      printf("'%c'\n" , value);
      }

      int main()
      {
      char ArrayA[5][7] = {'A'};
      char ArrayB[5][7] = {'B'};

      printf("ArrayA" );
      foo(ArrayA);

      printf("ArrayB" );
      foo(ArrayB);

      return 0;
      }


      -Mike


      Comment

      Working...