Public Group

# 2d array

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

## 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 on other sites
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 on other sites
what is this frobnicate(a, rows, columns);

error : 58 `frobnicate' undeclared (first use this function)

##### 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 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..

##### Share on other sites
also why are there 2 : free(a) and free(a)

##### 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.

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633704
• Total Posts
3013459
×

## Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!