Single dim array as a multidim array?

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

    Single dim array as a multidim array?

    Please could someone tell me how to use a single-dimensional array as a
    two-dimensional array? Is the following correct:

    int ROW_SIZE = 5;
    int COL_SIZE = 3;

    int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);

    arr[i *COLUMN_SIZE + j];

    will this only work for square arrays or all two-dim arrays ? Thanks :)


    Sona

  • Irrwahn Grausewitz

    #2
    Re: Single dim array as a multidim array?

    Sona <sona.gardner@n ospam.net> wrote in
    <3f534c51$1@cla rion.carno.net. au>:
    [color=blue]
    >Please could someone tell me how to use a single-dimensional array as a
    >two-dimensional array? Is the following correct:
    >
    >int ROW_SIZE = 5;
    >int COL_SIZE = 3;
    >
    >int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);[/color]
    Nit1: arr isn't an array, albeit you can apply the [] operator
    to an pointer to int (which it is).

    Nit2: the cast to int* is superfluous in C.
    [color=blue]
    >
    >arr[i * COLUMN_SIZE + j];[/color]
    This will work as long as i is in [0 ; ROW_SIZE-1]
    and j is in [0 ; COL_SIZE-1].

    Much like in a RealArray(tm):

    int realArr[YDIM][XDIM];
    realArr[ y ][ x ] ...
    [color=blue]
    >
    >will this only work for square arrays or all two-dim arrays ? Thanks :)[/color]
    Well, for square arrays i and j are interchangeable , as long as
    you use them in a consistently, but it works for all n-dimensional
    arrays, e.g.:

    int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );

    arr[ z * XDIM * YDIM + y * XDIM + x ] = 42;

    Irrwahn

    --
    If it's not on fire, it's a software problem.

    Comment

    • Irrwahn Grausewitz

      #3
      Re: Single dim array as a multidim array?

      Irrwahn Grausewitz <irrwahn@freene t.de> wrote in
      <l9m6lvkntsf2rg 9i6chc3ntnu8tph ah5vn@4ax.com>:
      [color=blue]
      >Well, for square arrays i and j are interchangeable , as long as
      >you use them in a consistently, but it works for all n-dimensional[/color]
      ^^^^<del>[color=blue]
      >
      >int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );[/color]
      ^^^^^^
      Damn, now I've copied this stupid cast!

      --
      Learn how to splel, dmanit!

      Comment

      • llewelly

        #4
        Re: Single dim array as a multidim array?

        Irrwahn Grausewitz <irrwahn@freene t.de> writes:
        [color=blue]
        > Irrwahn Grausewitz <irrwahn@freene t.de> wrote in
        > <l9m6lvkntsf2rg 9i6chc3ntnu8tph ah5vn@4ax.com>:
        >[color=green]
        >>Well, for square arrays i and j are interchangeable , as long as
        >>you use them in a consistently, but it works for all n-dimensional[/color]
        > ^^^^<del>[color=green]
        >>
        >>int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );[/color]
        > ^^^^^^
        > Damn, now I've copied this stupid cast![/color]

        That's ok. Weirdos who compile your code on boxen where int and int*
        are not the same size deserve undefined behavior. Especially if
        you forgot to include a header. Remember, all the world is a
        wintel32.

        (Note to c.l.c++ readers: that cast isn't necessary or safe in C++
        either; the alternatives are:
        vector<int> arr(ZDIM * YDIM * XDIM);
        int *arr= new [ZDIM * YDIM * XDIM * sizeof *arr];
        int *arr= static_cast<int *> malloc( ZDIM * YDIM * XDIM * sizeof *arr );
        )

        Comment

        • Jim Fischer

          #5
          Re: Single dim array as a multidim array?

          Sona wrote:[color=blue]
          > Please could someone tell me how to use a single-dimensional array as a
          > two-dimensional array? Is the following correct:
          >
          > int ROW_SIZE = 5;
          > int COL_SIZE = 3;
          >
          > int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);
          >
          > arr[i *COLUMN_SIZE + j];
          >
          > will this only work for square arrays or all two-dim arrays ? Thanks :)[/color]

          Consider the following C++ program

          <example>
          void foo(int **b, int rows, int cols)
          {
          for (int r = 0; r < rows; ++r) {
          for (int c = 0; c < cols; ++c) {
          b[r][c] = r*c + c;
          }
          }
          }

          int main()
          {
          int rows = 5;
          int cols = 3;
          int **a = 0;

          try {
          a = new int*[rows];
          a[0] = 0;
          a[0] = new int[rows * cols];
          for (int r = 1; r < rows; ++r)
          a[r] = a[r-1] + cols;

          // use the "2D array" 'a' here
          foo(a, rows, cols);
          }
          catch (...) {
          // whatever
          }

          // house keeping
          if ( a ) {
          delete[] a[0];
          delete[] a;
          }

          return 0;
          }
          </example>

          --
          Jim

          To reply by email, remove "link" and change "now.here" to "yahoo"
          jfischer_link58 09{at}now.here. com


          Comment

          • Kevin Goodsell

            #6
            Re: Single dim array as a multidim array?

            Irrwahn Grausewitz wrote:
            [color=blue]
            > Sona <sona.gardner@n ospam.net> wrote in
            > <3f534c51$1@cla rion.carno.net. au>:
            >
            >[color=green]
            >>Please could someone tell me how to use a single-dimensional array as a
            >>two-dimensional array? Is the following correct:
            >>
            >>int ROW_SIZE = 5;
            >>int COL_SIZE = 3;
            >>
            >>int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);[/color]
            >
            > Nit1: arr isn't an array, albeit you can apply the [] operator
            > to an pointer to int (which it is).
            >
            > Nit2: the cast to int* is superfluous in C.
            >[/color]

            It's a bit worse than superfluous. It can be dangerous (as can any cast).

            It's necessary in C++, but in C++ you normally shouldn't use 'malloc' at
            all. In nearly all cases you should use 'new' instead.

            -Kevin
            --
            My email address is valid, but changes periodically.
            To contact me please use the address from a recent posting.

            Comment

            • Irrwahn Grausewitz

              #7
              Re: Single dim array as a multidim array?

              Kevin Goodsell <usenet1.spamfr ee.fusion@never box.com> wrote in
              <3f539667@shkne ws01>:[color=blue]
              >
              >It's necessary in C++, but in C++ you normally shouldn't use 'malloc' at
              >all. In nearly all cases you should use 'new' instead.
              >[/color]
              From the use of malloc() in the OP's example I derived that this was a
              C-question - though it was cross-posted to c.l.c and c.l.c++, like your
              reply, and mine too...

              --
              I wish life had a scroll-back buffer.

              Comment

              • Al Bowers

                #8
                Re: Single dim array as a multidim array?



                Sona wrote:[color=blue]
                > Please could someone tell me how to use a single-dimensional array as a
                > two-dimensional array? Is the following correct:
                >
                > int ROW_SIZE = 5;
                > int COL_SIZE = 3;
                >
                > int *arr = (int*) malloc(sizeof(i nt) *ROW_SIZE*COL_S IZE);
                >
                > arr[i *COLUMN_SIZE + j];
                >
                > will this only work for square arrays or all two-dim arrays ? Thanks :)
                >[/color]

                I like:
                int i, **arr;
                arr = malloc(sizeof(* arr)*ROW_SIZE);
                for(i = 0;i < ROW_SIZE; i++)
                arr[i] = malloc(sizeof(* *arr)*COL_SIZE) ;
                arr[4][2] = 6; /* assuming successful allocations */

                This is only one of various ways you can do this. The faq
                demonstrates this technique and others at:


                --
                Al Bowers
                Tampa, Fl USA
                mailto: xal@abowers.com base.com (remove the x)
                Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


                Comment

                • foo

                  #9
                  Re: Single dim array as a multidim array?

                  llewelly <llewelly.at@xm ission.dot.com> wrote in message news:<86ekz0whj 9.fsf@Zorthluth ik.local.bar>.. .[color=blue]
                  > Irrwahn Grausewitz <irrwahn@freene t.de> writes:
                  >[color=green]
                  > > Irrwahn Grausewitz <irrwahn@freene t.de> wrote in
                  > > <l9m6lvkntsf2rg 9i6chc3ntnu8tph ah5vn@4ax.com>:
                  > >[color=darkred]
                  > >>Well, for square arrays i and j are interchangeable , as long as
                  > >>you use them in a consistently, but it works for all n-dimensional[/color][/color]
                  > ^^^^<del>[color=green][color=darkred]
                  > >>
                  > >>int *arr = (int*) malloc( ZDIM * YDIM * XDIM * sizeof *arr );[/color]
                  > > ^^^^^^
                  > > Damn, now I've copied this stupid cast![/color]
                  >
                  > That's ok. Weirdos who compile your code on boxen where int and int*
                  > are not the same size deserve undefined behavior. Especially if
                  > you forgot to include a header. Remember, all the world is a
                  > wintel32.
                  >
                  > (Note to c.l.c++ readers: that cast isn't necessary or safe in C++
                  > either; the alternatives are:
                  > vector<int> arr(ZDIM * YDIM * XDIM);
                  > int *arr= new [ZDIM * YDIM * XDIM * sizeof *arr];
                  > int *arr= static_cast<int *> malloc( ZDIM * YDIM * XDIM * sizeof *arr );
                  > )[/color]
                  IMHO, a better C++ alterantive would be to use either a
                  vector<vector<i nt> > object or even better yet, the following dynamic
                  2 dimensional array object:
                  template < class T, int ROW_T = 0, int COL_T = 0 >
                  class dynamic_2d_arra y
                  {
                  public:
                  dynamic_2d_arra y(int row, int col):m_row(row) ,m_col(col),
                  m_data((row!=0& &col!=0)?new T[row*col]:NULL){}
                  dynamic_2d_arra y():m_row(ROW_T ),m_col(COL_T), m_data(new
                  T[ROW_T*COL_T])
                  {if (!COL_T || !ROW_T) {int x[ROW_T] = {{ROW_T}};int y[COL_T] =
                  {{x[0]}};}}
                  ~dynamic_2d_arr ay(){if(m_data) delete []m_data;}
                  T* operator[](int i) {return (m_data + (m_col*i));}
                  T const*const operator[](int i) const {return (m_data +
                  (m_col*i));}
                  private:
                  const int m_row;
                  const int m_col;
                  T* m_data;
                  };
                  See following link for usuage example and for vector<vector<t ype> >
                  example:


                  Comment

                  • Irrwahn Grausewitz

                    #10
                    Re: Single dim array as a multidim array?

                    maisonave@axter .com (foo) wrote in
                    <c11783b0.03090 11241.44c4ed0d@ posting.google. com>
                    a lot of semi-cryptical C++ code. Please do not cross-post
                    C++ stuff to c.l.c.
                    --
                    When things look dark,
                    hold your head high so it can rain up your nose.

                    Comment

                    • LibraryUser

                      #11
                      Re: Single dim array as a multidim array?

                      foo wrote:[color=blue]
                      > Irrwahn Grausewitz <irrwahn@freene t.de> wrote in message[color=green]
                      > > maisonave@axter .com (foo) wrote in
                      > >
                      > > a lot of semi-cryptical C++ code. Please do not cross-post
                      > > C++ stuff to c.l.c.[/color][/color]
                      [color=blue][color=green][color=darkred]
                      > >>>>Nit2: the cast to int* is superfluous in C.[/color][/color]
                      >
                      > And please do not cross-post your superfluous C remarks to c.l.c++[/color]

                      You are both at fault here, not to mention the OP (who should not
                      have crossposted in the first place). Both of you should have
                      set followups. This is the appropriate mechanism to advise
                      across newsgroups, and prevent further confusion.

                      --
                      Replies should be to the newsgroup
                      Chuck Falconer, on vacation.

                      Comment

                      Working...