Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Dynamic Allocation of Multi-Dimensional Arrays - C/C++


chess_rock's Avatar
Member
0 0

Hey there everyone.

I've been studying a bit of C and C++ here, especially the part of object oriented programming, and i just banged my head in a big wall. I never really needed to dynamically allocate memory for multi dimensional arrays. It would be easy if i was dealing with simple vectors with my beautiful function called malloc and pointers. See the example below:

int *a;
int i=1000;

a=(int *)malloc(i*sizeof(int))```

In c++ i'd use the **new** keyword.

I'd be really grateful if anyone could explain me how to dynamically allocate values in a 2 dimensional array both in C and C++. Yet C is more important right now. I've been looking it up in google but i couldn't understand it really well. They mention creating arrays in structs and calling it with pointers, but i'd like to see some sort of code to understand it. 

fashizzlepop's Avatar
Member
0 0

C is not really object oriented. I assume you could use some creative programming to make it seem so but that might be more complicated than what your looking for. Hope this helps.


chess_rock's Avatar
Member
0 0

fashizzlepop wrote: C is not really object oriented. I assume you could use some creative programming to make it seem so but that might be more complicated than what your looking for. Hope this helps.

Well, yeah, i expressed myself badly. The thing is, i'm studying more deeply c++ now because i don't like c, but it is important for me to learn that in c as well as i'll be seeing this thing in university soon. We unfortunately study c and not c++ :(


ynori7's Avatar
Future Emperor of Earth
0 0

I believe this is how you create a multidimensional array in C/C++, though it's been a while so I could be wrong.

int i=10;
int j=1000;

//make an array with 10 sets of 1000 ints
a=(int *)malloc(i*sizeof(int*));
for(int x=0; x<i; x++)
{
    a[x] = (int *)malloc(j*sizeof(int)); 
}```
Not entirely sure if that was what you were looking for.

chess_rock's Avatar
Member
0 0

ynori7 wrote: I believe this is how you create a multidimensional array in C/C++, though it's been a while so I could be wrong.

int i=10;
int j=1000;

//make an array with 10 sets of 1000 ints
a=(int *)malloc(i*sizeof(int*));
for(int x=0; x<i; x++)
{
    a[x] = (int *)malloc(j*sizeof(int)); 
}```
Not entirely sure if that was what you were looking for.

Thanks a lot ynori :) That's exactly what i was looking for. I didn't realize i needed to add a double pointer (int **a). That makes it much clearer :) I'll program something soon to test this.

btw, sorry for taking too long to reply. Was away all day long. And again, thanks a lot!