# Coverting 2d static array to dynamic

Page 1 of 1

## 12 Replies - 1644 Views - Last Post: 26 February 2013 - 10:11 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=313665&amp;s=d5e79304610271eef382c60c3af6fc0a&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 osu1

Reputation: 0
• Posts: 99
• Joined: 17-June 12

# Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:04 PM

Hello guys, today I had a quick question after trying out something and failing on my by trying to convert a 2d array to dynamic.

How can I convert my array matrix into dynamic? I know this code works in certain compilers but some wont do it so I want to converted it to dynamic , I used other methods like initializing the array by "looping" but it did not work at all. Right now my code only works if I use a number say 5 or 3 for n and it works well but I need to work from the users input.Thank you for your time!

```#include <fstream>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

void CalculateOddMagicSquare(int n)
{
int matrix[n][n];

int nsqr = n * n;
int i=0, j=n/2;     // start position

for (int k=1; k<=nsqr; ++k)
{
matrix[i][j] = k;

i--;
j++;

if (k%n == 0)
{
i += 2;
--j;
}
else
{
if (j==n)
j -= n;
else if (i<0)
i += n;
}
}

for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
cout << matrix[x][y] << " ";
}
cout << endl;
}
}

int main()
{
int n;
cin >> n;
CalculateOddMagicSquare(n);
return 0;
}
```

This post has been edited by osu1: 26 February 2013 - 08:05 PM

Is This A Good Question/Topic? 0

## Replies To: Coverting 2d static array to dynamic

### #2 jjl

• Engineer

Reputation: 1270
• Posts: 4,998
• Joined: 09-June 09

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:11 PM

You can do this one of two ways. You can create the dynamically an array of pointers on the heap, then you can point each pointer to dynamic chunks of memory (these would represent the rows).

You can see that dynamic 2D arrays are a little complicated due to all of the memory allocation. Since you are new to dynamic memory, I recommend create a large dynamic 1D array on the heap (size of n*n). You can then map your 2D indices to 1D indices.

i.e.

```void calculateOddMagicSquare(int n) {
//allocate n * n integers on heap
int *matrix = malloc(n * n * sizeof(int));

//to access element (i, j), do the following
matrix[i * n +j] = 1;

```

Remember that dynamic memory is not like other memory. Matrix will not deallocate at the end of the current stack frame, therefore you need explicitly deallocate it using free when your done with it.

i.e.
```free(matrix);

```

This post has been edited by jjl: 26 February 2013 - 08:13 PM

### #3 osu1

Reputation: 0
• Posts: 99
• Joined: 17-June 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:19 PM

Thank you but I already tried that. 1D is very easy to do , but I couldn't do it when it was 2D. I don't know how to completely change the whole thing to dynamic, I thought it was a simple conversion but turns out it is not.

This post has been edited by GunnerInc: 26 February 2013 - 08:20 PM
Reason for edit:: Quote be gone

### #4 Skydiver

• Code herder

Reputation: 6071
• Posts: 20,894
• Joined: 05-May 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:20 PM

Ummm. Line 6 in the OP indicates that he is using C++. So what is wrong with using a vector<> of vectors<>? Or an array<> of array<>?

This post has been edited by Skydiver: 26 February 2013 - 08:23 PM

### #5 osu1

Reputation: 0
• Posts: 99
• Joined: 17-June 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:22 PM

Skydiver, on 26 February 2013 - 08:20 PM, said:

Ummm. Line 6 in the OP indicates that he is using C++. So what is wrong with using a vector of vectors?

I thought it was required to do arrays so I based it on all that. Vectors I saw was going to be easier but as of now it might too late to change my entire project to vectors.

I edited my code to where I initialized it as

```int* matrix = new int[n*n]
```

to allocate a dynamic square array,but the variables i,j and x,y give me a error that they need to be of type array or pointer.

This post has been edited by osu1: 26 February 2013 - 08:30 PM
Reason for edit:: Quote go poof

### #6 jjl

• Engineer

Reputation: 1270
• Posts: 4,998
• Joined: 09-June 09

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:30 PM

Quote

Ummm. Line 6 in the OP indicates that he is using C++. So what is wrong with using a vector<> of vectors<>? Or an array<> of array<>?

When I glanced at his header files I could of swore I saw stdio.h, rather than iostream. Very strange.

Quote

Thank you but I already tried that. 1D is very easy to do , but I couldn't do it when it was 2D.

Ok dynamic 2D arrays are described in my earlier post. Essentially you need to dynamically create an array of pointers, then for each pointer allocate memory for each row. Since this is a dynamic array of pointers, you need to use a double pointer (a pointer to an array of pointers).
```int **matrix = new int*[n]; //weird syntax, but it is a dynamic array of pointers

```

Now for each pointer from 0 ... n-1, you need to allocate an array of size n
```for(int i=0; i<n; i++)
matrix[i] = new int[n]; //each chunk of memory is a row in the matrix

```

From here on out, you should be good to go since the bracket array notation will work with dynamic 2D arrays.

The biggest difference with dynamic and regular 2D arrays, is that the memory is that the data is not laid out continuously across the heap. Rather, each index in the array is a pointer to somewhere else on the heap where the memory resides. Not a big deal here, but it is something to keep in mind.

This post has been edited by jjl: 26 February 2013 - 08:31 PM

### #7 osu1

Reputation: 0
• Posts: 99
• Joined: 17-June 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:36 PM

Ok dynamic 2D arrays are described in my earlier post. Essentially you need to dynamically create an array of pointers, then for each pointer allocate memory for each row. Since this is a dynamic array of pointers, you need to use a double pointer (a pointer to an array of pointers).
```int **matrix = new int*[n]; //weird syntax, but it is a dynamic array of pointers

```

Now for each pointer from 0 ... n-1, you need to allocate an array of size n
```for(int i=0; i<n; i++)
matrix[i] = new int[n]; //each chunk of memory is a row in the matrix

```

From here on out, you should be good to go since the bracket array notation will work with dynamic 2D arrays.

The biggest difference with dynamic and regular 2D arrays, is that the memory is that the data is not laid out continuously across the heap. Rather, each index in the array is a pointer to somewhere else on the heap where the memory resides. Not a big deal here, but it is something to keep in mind.
[/quote]

I tried to do the code you did and my program will compile but won't run. I understand this, so I only do one for a row but not for the columns as you described dynamic arrays above. Was there something additional i was not able to grasp? I replaced my code as such.

```void calculateoddmagicSquare(int n)
{

int** matrix = new int*[n];
for (int i=0; i<n; i++)
matrix[i]=new int[n];

int nsqr= n*n;
int i=0,j=n/2; //start position
```

This post has been edited by GunnerInc: 26 February 2013 - 08:55 PM
Reason for edit:: Quote go poof

### #8 jjl

• Engineer

Reputation: 1270
• Posts: 4,998
• Joined: 09-June 09

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:42 PM

The allocation looks fine, post the entire code

### #9 osu1

Reputation: 0
• Posts: 99
• Joined: 17-June 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:50 PM

jjl, on 26 February 2013 - 08:42 PM, said:

The allocation looks fine, post the entire code

Here it is. Before all of this it printed a magic square just fine now it compiles but it won't run. Thank you for your time!

```#include <iostream>

using namespace std;

void calculateoddmagicSquare(int n)
{

int** matrix = new int*[n];
for (int i=0; i<n; i++)
matrix[i]=new int[n];

int nsqr= n*n;
int i=0,j=n/2; //start position

for (int k=1; k<= nsqr; ++k)
{
matrix[i][j]=k;

i--;
j++;

if(k%n==0)
{
i +=2;
--j;
}
else
{
if(j==n)
j-=n;
else if ( i<0)
i+=n;
}
}

int count;
for(int x=0;x<n;x++)
{
count=0;
for ( int y=0; y<n;y++)
{
count += matrix[x][y];
cout << matrix[x][y]<< "";
}
cout << endl;
}
cout << count;
}

int main()
{
int n;
cin >> n;
while (n <= 0)
{
calculateoddmagicSquare(n);
cin >> n;
}
return 0;
}

```

### #10 jjl

• Engineer

Reputation: 1270
• Posts: 4,998
• Joined: 09-June 09

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 08:55 PM

```int main()
{
int n;
cin >> n;
while (n <= 0)
{
calculateoddmagicSquare(n);
cin >> n;
}
return 0;
}

```

Look at your loop condition very closely

### #11 osu1

Reputation: 0
• Posts: 99
• Joined: 17-June 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 09:08 PM

I fixed the condition thank you, but one quick question.My output is aligned well when printed when it is single digits printed say 1,2 3, but when mixed it is like 2, 45 and such in rows and columns in the matrix it is not aligned in the square matrix output. I tried when cout the matrix to use space in "" such as " " . Thank you!

*** EDIT ***

This post has been edited by GunnerInc: 26 February 2013 - 09:09 PM
Reason for edit:: Quote be gone

### #12 Skydiver

• Code herder

Reputation: 6071
• Posts: 20,894
• Joined: 05-May 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 09:10 PM

You could use setw() to set how wide you want your printed numbers to be.

### #13 osu1

Reputation: 0
• Posts: 99
• Joined: 17-June 12

## Re: Coverting 2d static array to dynamic

Posted 26 February 2013 - 10:11 PM

Thank you very much for your assistance guys!