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!

How to initialize 3-D array

Status
Not open for further replies.

sedawk

Programmer
Feb 5, 2002
247
US
I am this method to initialize 2D array:

// begin code
int **a, int r, int c;
int i;
int **a = (int *) malloc (r * sizeof (int *));
for (i=0;i<c;i++)
*a = (int *) malloc(c * sizeof(int));
// end code

if I extend this to 3-D array, I got error:
// begin code
int ***a, int n, int r, int c;
int i, j;
int *** = (int **) malloc (n * sizeof (int **));
for (i = 0; i < n; i++) {
int **a = (int *) malloc (r * sizeof(int *));
for (j = 0; j < r; j++) {
*a[j] = (int *) malloc (c * sizeof(int));
}
}
// end code

What is wrong? What is the correct way?


 
Please remember to use the [ignore]
Code:
[/ignore] tags, especially since i subscripts turn your post into italics.

Code:
int ***a;
int n, r, c;  // suitably initialised
a = malloc ( n * sizeof *a );
for ( i = 0 ; i < n ; i++ ) {
    a[i] = malloc ( r * sizeof *a[i] );
    for ( j = 0 ; j < r ; j++ ) {
        a[i][j] = malloc ( c * sizeof *a[i][j] );
    }
}
Two points to note
1. there is no cast on the return result of malloc
If you get a warning about int to pointer casting, it means you need to include stdlib.h
If you get a warning about casting void* pointers, it means you're compiling C++ code (in which case you should either change your compiler options to compile C, or start using the new operator from C++)

2. Note how the size is calculated using sizeof
Code:
p = malloc ( num * sizeof *p );
Make the compiler do the work, and you no longer have to think about whether this particular size is supposed to be int or int* or whatever. It is also self-adjusting should you ever change the type you're allocating (say change from int to double).

--
 
Ah, Sorry about this: I should be more precise 'cause I just typed the codes without copy-and-paste the codes I actually compiled(it is on another machine).

I did have the cast of malloc, just like what I did with 2-D array initialization. Also, I do have stdlib.h and malloc.h(I am using VC6++) because I just modified everything based on my 2-D array. This part should be fine.

The error is about &quot;can't convert from int * to int **&quot; or something like that, I will post the error message after I get access to the machine. I was thinking the way I did that is (very) wrong so never mind posting the details and i just want to know the correct way.

p = malloc (num * sizeof *p) is a good try. Thanks for your tips.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top