Creating a two dimentional array.

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. :)
dear Bazzy...

i am not asking how we can do it, it was about different ways of doing it!!
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
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.
i apologize if you think i was rude. :(
that solution i already know, i was just interested in knowing some other way.. thats it.
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
hmmm... you mean a single array with 25 elements??

so that mean arr[2][3] will be
arr[5 * 2 + 3].. correct?
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
Topic archived. No new replies allowed.