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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2d runtime arrays

Status
Not open for further replies.

bitwise

Programmer
Mar 15, 2001
269
US
How do I create a 2-dimensional runtime array in C? I know how many "columns" it has and that is 3 but the number of rows is determined at runtime. How do I properly allocate the room for that?

Thanks,
-bitwise
 
Is the following what you need?

char* y="hello";
char*** x;
int i,j;
x=(char***)malloc(num_cols*num_rows*sizeof(char*));
for(i=0;i<numcols;i++)
for(j=0;j<numcols;j++)
x[j]=y; John Fill

ivfmd@mail.md
 
More clear way for compiler:

/* this is pointer to array of 3 integers */
int (*paiArray)[3] = NULL;
/* !!! this is not a *apiArray[3] what is the array of 3 pointers to int */


/* allocate by one call to malloc x is a number of your rows*/
paiArray = (int(*)[3])malloc(x*sizeof(int[3]));

/* Easy to use :) */
paiArray[0][1] = 3;
printf(&quot;A:%d\n&quot;,paiArray[0][1]);

/* free array */
free(paiArray);

This is the easy way to use 2 dim array if you know the number of colums. And it makes code more understandable for programmer and compiler.

Regards.
 
One thing that would make it even more understandable is to drop the cast on malloc():

paiArray=malloc(x*sizeof(int[3]));

In C, pointers to void can be converted back and forth to other pointer types implicitly without any loss of information.

And better for code maintenance:

paiArray=malloc(x * sizeof *paiArray);

If the type of paiArray changes (say to pointer to array 15 of int), you only have to make changes at the point of the definition of paiArray.

Russ
bobbitts@hotmail.com
 
But in future you probably will want to use this code in C++.
For example we are use both code in our programm C and C++ and sometime you need to call C++ from C so you just compile it as C++. In this case (void*) will not be cast by default to (int(*)[3]) at least in gcc, you will have a compilation error. So it is never hurt to use a cast.
Of cause you can skip this cast for your homework.
Also this type int(*)[3] can help you to pass this array as an argument in some function
int func(int(*)[3] in_paiArray)
{
}
I have spent some time to find the right type for this argument.

But second advice about using paiArray to get it size is very wise:)
 
That's a good point and this is an important difference between C and C++. C++, indeed, doesn't allow such conversions to occur implicitly so the cast is required if you were using Lim's example in C++ code.

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Similar threads

Replies
9
Views
210
  • Locked
  • Question
Replies
6
Views
42
Replies
2
Views
122
Replies
1
Views
144

Part and Inventory Search

Sponsor

Back
Top