Jump to content
  • Advertisement
Sign in to follow this  
iamspecial

2d array

This topic is 3721 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

how to dynamically allocate a 2d arry using malloc in c language the user will input a number and then i want a 2d arry to be dynamically allocated suppose user enters 25 , then the array will have 5 rows and 5 coloumns how to do this i suppose we have to do something like this int **a; for(int i=0;i<sqrt(n);i++) for(int j=0;j<sqrt(n);j++) a[j]=(int*)malloc(sizeof(int)); but it is giving a error like invalid conversion from `int*' to `int'

Share this post


Link to post
Share on other sites
Advertisement
a doesn't exist until you assign something to a. So, it would probably look like:

int rows = sqrt(n);
int columns = n / rows;
int i;

int **a = malloc(sizeof(int*) * rows);
for (i = 0; i < rows; ++i)
a = malloc(sizeof(int) * columns);

frobnicate(a, rows, columns);

for (i = 0; i < rows; ++i)
free(a);

free(a);

Share this post


Link to post
Share on other sites
It is a dummy name used to represent anything. It's purpose is not a call to the function, but to demonstrate how to use the array you just allocated.

Share this post


Link to post
Share on other sites
ok ...
but still i cant understand the above code


int **a = malloc(sizeof(int*) * rows);
for (i = 0; i < rows; ++i)
a = malloc(sizeof(int) * columns);

i need a further explaination..
thanks in advance

Share this post


Link to post
Share on other sites
The first call to malloc allocates a number of pointers representing the rows (or columns) of the 2D array. The second set of calls to malloc in the loop allocates the individual columns (or rows). You need to do this becuase you cannot allocate arrays with more than one unknown dimension. If you need a 2D array with both dimensions unknown, you must allocate both dimensions individually.

The free-part is the same, only reverse. You must free exactly what you allocate.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!