[try Beta version]
Not logged in

 
Creating a two dimentional array.

Apr 1, 2009 at 12:11pm
Guys...
was going through a post in beginner section..

Creating a 2 dimensional array in C


out of curiosity, if we have this:

int **ptr;

what can be different ways we can allocate memory to it and use it??
lets say we want a 5 X 5 matrix.

Thanks. :)
Apr 1, 2009 at 1:43pm
Apr 1, 2009 at 4:02pm
dear Bazzy...

i am not asking how we can do it, it was about different ways of doing it!!
Apr 1, 2009 at 4:30pm
closed account (S6k9GNh0)
1
2
3
4
5
6
int bob[x][x]; //Initialization

int **ptr; //pointer for storing arrays. //I think

ptr = &bob; //ptr equal to reference in memory of bob array.
//That's really all there is...Also you can use the new sytax as well... 


And I haven't done it in a while so I dont' know the correct way to access the members. :"(
Last edited on Apr 1, 2009 at 4:31pm
Apr 1, 2009 at 4:31pm
Dear writeonsharma: your reply to bazzy is nonsensical. The article shows you two different ways of doing it. What's the problem? If someone else knows other ways of doing it then perhaps they will post another alternative in addition to that.
Apr 1, 2009 at 4:41pm
i apologize if you think i was rude. :(
Apr 1, 2009 at 4:42pm
that solution i already know, i was just interested in knowing some other way.. thats it.
Apr 1, 2009 at 4:48pm
If you are looking for other methods of creating an (eg) 5 x 5 Matrix, you can use pseudo-2D arrays:
1
2
3
4
//fixed size:
int mtrx[5*5];
//dynamically allocated:
int *pmtrx = new int[5*5];
Last edited on Apr 1, 2009 at 4:48pm
Apr 1, 2009 at 4:51pm
hmmm... you mean a single array with 25 elements??

so that mean arr[2][3] will be
arr[5 * 2 + 3].. correct?
Apr 2, 2009 at 2:24pm
In C++, you can always do something like this:

1
2
3
4
5
6
7
//Create your pointer
int **ptr;
//Assign first dimension
ptr = new int*[5];
//Assign second dimension
for(int i = 0; i < 5; i++)
	ptr[i] = new int[5];

I'm using a technique like this to create a dynamic 3D array. It works, though you will also have to loop delete[] to delete the array properly.

As for C, I don't know how to dynamically allocate memory there, sorry.
Last edited on Apr 2, 2009 at 2:30pm
Topic archived. No new replies allowed.