Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Two-Dimensional array allocation

Status
Not open for further replies.

amarti44

Programmer
Feb 16, 2001
23
0
0
US
Please help me to understand this function to allocate a 2D array.
int** ArrayAlloc(int rows, int cols, int size)
{
int i;
int** pp;

pp = (int**) malloc(rows * sizeof(int*));
/* check for error */
pp[0] = (int*) malloc(rows * cols * size);
/* check for error */
for(i = 1; i < rows; ++i)
pp = &(pp[0][i * cols * size]);
return pp;
}
 
this does not look like it works and it is a bit confusing to read. why not just declare the 2d array as

int pp[rows][cols]... not in the function but in place of it?

The above just changes the memory address of pp and does not assign it an int** but an int*.

if you prefer you could:
pp = &((int*)malloc(rows*cols*sizeof(int)));

this will give you the same amount of memory allocated and you can do with it what you will.

Matt
 
I suggest you:
int* ArrayAlloc(int rows, int cols,ins size)
{
int* pi;
pi=(int*)malloc(rows*cols*size);
return pi;
}
An R-dimentions space in computer memory will look always as 1Dimention array John Fill
1c.bmp


ivfmd@mail.md
 
to declare a 2 dimensional array in C using malloc, you have to do this:

int** pp;

for(int i = 0; i < 100; i ++)
*(pp+i) = (int*)malloc(sizeof(int) * 100);

you have to allocate space for EVERY row in in the array

&quot;pp = (int**) malloc(rows * sizeof(int*));&quot; will only allocate space for ONE row, hence causing an error if you try to access a row greater than pp[1][99]
 
Zyrenthian,
what does pp = &((int*)malloc(rows*cols*sizeof(int))); mean?
malloc returns a number, not a variable, and operator & there is at least unexpected.

xGrob, what does pp+i mean, have you forgotten what so far pp is a not initialized pointer to pointer? You'll generate so a memory crash.
correct is:
int**pp;
int* p;
int nRows=100;
int nColumns=10;
p=(int*)malloc(nRows*nColumns*sizeof(int));
pp=(int**)malloc(nColumns*sizeof(int*));
for(int i=0;i<nColumns;i++)
{
pp=p[i*nColumns];
}
John Fill
1c.bmp


ivfmd@mail.md
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top