Strcpy function from a 3D array to an 2D array? Check?

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 877 Views - Last Post: 03 September 2013 - 04:56 PM Rate Topic: -----

#16 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3644
  • View blog
  • Posts: 11,410
  • Joined: 05-May 12

Re: Strcpy function from a 3D array to an 2D array? Check?

Posted 02 September 2013 - 10:49 PM

I hope that you do realize that char dest[210][13] and char source[5][42][13] are laid out in memory exactly the same way and so a simple memcpy() call is going to be sufficient to get the effect that you are looking for.
Was This Post Helpful? 0
  • +
  • -

#17 defjamvan  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 02-September 13

Re: Strcpy function from a 3D array to an 2D array? Check?

Posted 03 September 2013 - 07:50 AM

It's an assignment and I can't use strcpy(). Virus? Never.

No strcpy(), memcpy() or similar functions are allowed.
Was This Post Helpful? 0
  • +
  • -

#18 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3644
  • View blog
  • Posts: 11,410
  • Joined: 05-May 12

Re: Strcpy function from a 3D array to an 2D array? Check?

Posted 03 September 2013 - 04:56 PM

You simply have to understand how C and C++ lays out its data is row major order. Taking the sample from Wikipedia:

The layout of this:
int A[2][3][4] = {{{1,2,3,4}, 
                   {5,6,7,8}, 
                   {9,10,11,12}}, 
                  {{13,14,15,16}, 
                   {17,18,19,20}, 
                   {21,22,23,24}}};


Looks like this in memory:
Address     Contents
A + 0           1
A + 1           2
A + 2           3
A + 3           4
A + 4           5
A + 5           6
:
A + 22         23
A + 23         24



Now let's look at a 2 dimensional array:
int A[6][4] = {{1,2,3,4}, 
               {5,6,7,8}, 
               {9,10,11,12}, 
               {13,14,15,16}, 
               {17,18,19,20}, 
               {21,22,23,24}};


In memory it looks like this:
Address     Contents
A + 0           1
A + 1           2
A + 2           3
A + 3           4
A + 4           5
A + 5           6
:
A + 22         23
A + 23         24



And now let's look at a 1 dimensional array:
int A[24] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24};


And guess what... the layout in memory still looks like this:
Address     Contents
A + 0           1
A + 1           2
A + 2           3
A + 3           4
A + 4           5
A + 5           6
:
A + 22         23
A + 23         24



So with that knowledge you can map any n-dimensional array in C into a 1 dimensional array, and back again.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2