• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 301
  • Last Modified:

Multidimensional Array Dynamically Allocated

I am wondering how to implement a multidimensional array based on a users input.

Basically the user will enter data that will determine how many rows there are and I have a fixed number of columns.  How can I dynamically allocate this to work?

Thanks
Darrell
0
larockd
Asked:
larockd
  • 3
1 Solution
 
BonevCommented:
Suppose COLUMNS is the fixed number of columns.
Rows is user input number of rows.

/* allocation */
int* pArray;
pArray = (int*)malloc(sizeof(int)*COLUMNS*Rows);

/* access to row i and column j */
int item;
item = pArray[COLUMNS*i+j];

0
 
BonevCommented:
To release the memory use free(pArray);
0
 
larockdAuthor Commented:
Iwas able to use your code and get it to work.  I do have some questions on the theory behind this.

It would appear as if this is a single dimensional array.  I say this because all the memory is accesses sequentially, but isnt that a property of a multidimensional array.  

I was wondering if you could break down the malloc statement for me..


    pArray = (int*)malloc(sizeof(int)*COLUMNS*Rows);

I am allocating the size of int * Columns * rows which allocates Columns * rows of integers that pArray points to.  Why did you type cast malloc as (int *) is this because it is a pointer to begin with?


Thanks


0
 
BonevCommented:
Well, the multidimensional arrays are just an abstraction, because the computer memory is linear (one dimension). The programming languages provide means to work with MD arrays, but in fact their representation is linear. Since you don't know the size of the dimensions, you should simulate what the compiler does for you.
You're correct about the malloc statement.
Your 2D array actually is a sequence of Rows single dimensional arrays of size COLUMNS. If you want to access row i and column j, you need first to reach the first item of i-th 1D array using COLUMNS*i, and then you have to point to the j-th item in that array, adding j.


0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now