473,396 Members | 1,858 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

dynamically allocating a 2d array

What is the correct way of dynamically allocating a 2d array ?

I am doing it the following way. Is this correct ?

#include <stdlib.h>
int main(void)
{
int (*arr)(3);
arr = malloc(sizeof(*arr) * 4);
/* I want to dynamically allocate
int arr[4][3] */

arr[2][3] = 100; /* Can I initialize the 3rd column of
2nd row in this manner ? */
}

Thanx in advance for any help ...

Nov 15 '05 #1
10 2541
ju**********@yahoo.co.in wrote:
What is the correct way of dynamically allocating a 2d array ?
There are a few correct ways.
I am doing it the following way. Is this correct ?

#include <stdlib.h>
int main(void)
{
int (*arr)(3);
This is wrong, it should be 'int (*arr)[3]' (pointer to array of three
ints). Even better, use a typedef: "typedef int row[3];".
arr = malloc(sizeof(*arr) * 4);
/* I want to dynamically allocate
int arr[4][3] */

arr[2][3] = 100; /* Can I initialize the 3rd column of
2nd row in this manner ? */


This code is correct.

An alternative way which works even it the presence of variable dimensions
is to allocate an array of size X*Y and then compute the index in the 1D
array from the position in the 2D array and its size.

Uli

Nov 15 '05 #2
ju**********@yahoo.co.in wrote:
What is the correct way of dynamically allocating a 2d array ?
This is a FAQ, see section 6.16 in
http://www.faqs.org/faqs/C-faq/faq/

I suggest you read the whole thing, once you got it.
I am doing it the following way. Is this correct ?
At least you could've tried to compile it before you posted.
#include <stdlib.h>
int main(void)
{
int (*arr)(3);

syntax error
<snip>

Rhetorical question: What would you do with a pointer to a function
taking constant 3 returning int, anyway?

Best regards.
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc frequent answers: http://benpfaff.org/writings/clc.
Nov 15 '05 #3

Irrwahn Grausewitz wrote:
ju**********@yahoo.co.in wrote:
What is the correct way of dynamically allocating a 2d array ?


This is a FAQ, see section 6.16 in
http://www.faqs.org/faqs/C-faq/faq/

I suggest you read the whole thing, once you got it.
I am doing it the following way. Is this correct ?


At least you could've tried to compile it before you posted.
#include <stdlib.h>
int main(void)
{
int (*arr)(3);

syntax error
<snip>

Rhetorical question: What would you do with a pointer to a function
taking constant 3 returning int, anyway?

Sorry, it was a typo. I meant int (*arr)[3].

Nov 15 '05 #4
Stick to the following rule:
-Generally, an array name in an expression is evaluated as a pointer to
its first element.

Thus,
int array[Y][X] is a 2d array, an array of Y arrays of X integers.
You can write its dynamic counterpart as follows:
int (*array)[X] which is a pointer to an array of X integers.
And then allocate it dynamically via malloc:
array = malloc(sizeof(*array) * Y );

Nov 15 '05 #5

i have a soln. just try it out it might work:
for dynamically allocating a 2d array of let it be something like
a[5][8].
int **t;
t=(int **)malloc(5*2);
for(i=0;i<5;i++)
{
*(t+i)=(int *)malloc(8*2);
}

Nov 15 '05 #6
sahu wrote on 11/09/05 :
i have a soln. just try it out it might work:
for dynamically allocating a 2d array of let it be something like
a[5][8].
int **t;
t=(int **)malloc(5*2);
Why 5 * 2 ? What is the cast made for ?

int **t; = malloc (5 * sizeof *t);

if (t != NULL)
{
for(i=0;i<5;i++)
Better to define some abstraction for this hard coded '5' ...
{
*(t+i)=(int *)malloc(8*2);
why 8 * 2 ? Be simple:

t[i] = malloc (8 * sizeof *t[i]);
}


The generic expression to allocate a variable (n = 1) or an array of n
variables of type T is:

T *p = malloc (n * sizeof *p);

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"
Nov 15 '05 #7
"Nerox" <ne****@gmail.com> writes:
Stick to the following rule:
-Generally, an array name in an expression is evaluated as a pointer to
its first element.


Unless it's the argument of a sizeof or unary "&" operator.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #8
Ulrich Eckhardt wrote:
ju**********@yahoo.co.in wrote:
What is the correct way of dynamically allocating a 2d array ?


There are a few correct ways.
I am doing it the following way. Is this correct ?

#include <stdlib.h>
int main(void)
{
int (*arr)(3);


This is wrong, it should be 'int (*arr)[3]' (pointer to array of
three ints). Even better, use a typedef: "typedef int row[3];".
arr = malloc(sizeof(*arr) * 4);

arr[2][3] = 100; /* Can I initialize the 3rd column of
2nd row in this manner ? */


This code is correct.


arr[2][3] is the 4th column of the 3rd row. Arrays index
from 0 in C. Depending on how you read the Standard,
accessing arr[2][3] either causes undefined behaviour, or
ends up accessing arr[3][0].

Nov 15 '05 #9
ju**********@yahoo.co.in wrote:
What is the correct way of dynamically allocating a 2d array ?

I am doing it the following way. Is this correct ?

#include <stdlib.h>
int main(void)
{
int (*arr)(3);
I'm assuming you meant

int (*arr)[3];
arr = malloc(sizeof(*arr) * 4);
/* I want to dynamically allocate
int arr[4][3] */
I'm assuming you meant

int arr[3][4]

arr[2][3] = 100; /* Can I initialize the 3rd column of
2nd row in this manner ? */
}

Thanx in advance for any help ...


Well, it's different (never thought to do it that way before). It
appears to work, though. However, this method requires one dimension
be fixed. If you want to allocate a 2D array of int and be able to
specify both dimensions dynamically, here's one method:

#include <stdlib.h>

int **new2DIntArray(size_t rows, size_t cols)
{
int **arr;
int mallocError = 0;
size_t lastRow = 0;

arr = malloc(sizeof arr[0] * rows);
if (arr)
{
size_t i;
for (i = 0; i < rows && !mallocError; i++)
{
arr[i] = malloc(sizeof arr[i][0] * cols);
if (arr[i])
{
size_t j;
lastRow = i;
for (j = 0; j < cols; j++)
{
arr[i][j] = 0;
}
}
else
{
mallocError = 1;
break;
}
}

if (mallocError)
{
size_t i;
for (i = lastRow; i >= 0; i--)
{
free(arr[i]);
}
free(arr);
arr = NULL;
}
}

return arr;
}

int main(void)
{
int **arr1 = new2DIntArray(4,3); /* int arr[4][3] */
int **arr2 = new2DIntArray(3,4); /* int arr[3][4] */
/* etc. */

/* do something with arrays */

return 0;
}

You'll want to add another function to free up the arrays when you're
done with them, but that should be straightforward (basically it's the
if(mallocError) branch above).

Nov 15 '05 #10
On 12 Sep 2005 03:56:48 -0700, "John Bode" <jo*******@my-deja.com>
wrote:
ju**********@yahoo.co.in wrote:
What is the correct way of dynamically allocating a 2d array ?

I am doing it the following way. Is this correct ?

#include <stdlib.h>
int main(void)
{
int (*arr)(3);
I'm assuming you meant

int (*arr)[3];
arr = malloc(sizeof(*arr) * 4);
/* I want to dynamically allocate
int arr[4][3] */


I'm assuming you meant

int arr[3][4]


I hope not. He has allocated space for an array of 4 arrays of 3 int
each.

arr[2][3] = 100; /* Can I initialize the 3rd column of
2nd row in this manner ? */
The third column of the second row is arr[1][2].
}

Thanx in advance for any help ...
Well, it's different (never thought to do it that way before). It
appears to work, though. However, this method requires one dimension
be fixed. If you want to allocate a 2D array of int and be able to
specify both dimensions dynamically, here's one method:

#include <stdlib.h>

int **new2DIntArray(size_t rows, size_t cols)
{
int **arr;
int mallocError = 0;
size_t lastRow = 0;

arr = malloc(sizeof arr[0] * rows);
if (arr)
{
size_t i;
for (i = 0; i < rows && !mallocError; i++)
{
arr[i] = malloc(sizeof arr[i][0] * cols);
if (arr[i])
{
size_t j;
lastRow = i;
for (j = 0; j < cols; j++)
{
arr[i][j] = 0;
}
}
else
{
mallocError = 1;
break;
}
}

if (mallocError)
{
size_t i;
for (i = lastRow; i >= 0; i--)


This for loop can never end. size_t is an unsigned type so i will
always be >= 0.
{
free(arr[i]);
}
free(arr);
arr = NULL;
}
}

return arr;
}

int main(void)
{
int **arr1 = new2DIntArray(4,3); /* int arr[4][3] */
int **arr2 = new2DIntArray(3,4); /* int arr[3][4] */
/* etc. */

/* do something with arrays */

return 0;
}

You'll want to add another function to free up the arrays when you're
done with them, but that should be straightforward (basically it's the
if(mallocError) branch above).

<<Remove the del for email>>
Nov 15 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Peter Olcott | last post by:
I want to be able to efficiently build data structures at run-time. These data structures need to be accessed with minimal time. The only a few ways that come immediately to mind would be some...
5
by: csnerd | last post by:
I have a really simple question. What is the difference between allocating memory following way: #1 int main(int argc,char* argv) { char str)+1]; return 0; }
4
by: Ovid | last post by:
Hi all, I'm having a problem trying to create a 2D array whose dimensions are determined at runtime. Below my signoff is a minimal test case that hopefully demonstrates what I'm trying to do. ...
7
by: Fabian Wauthier | last post by:
Hi list, I am trying to dynamically grow a 2 dimensional array (Atom ***Screen) of pointers to a struct Atom (i.e. the head of a linked list). I am not sure if this is the right way to do it: ...
3
by: yogi | last post by:
Hi guys, I'm trying to write a program that will read in a series of files and create a 3D array from the files read in for converting 2D images to 3D objects. The values read in will be...
94
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring...
6
by: bwaichu | last post by:
Is my understanding of the allocation of these correct? I used fixed sized allocations for the example below, so I realize there is some optimization that can be done to those. I would like to...
3
by: Samant.Trupti | last post by:
HI, I want to dynamically allocate array variable of type LPWSTR. Code looks like this... main() { LPWSTR *wstr; int count = Foo (wstr); for (int i = 0; i < count; i++) //print each...
28
by: Trups | last post by:
HI, I want to dynamically allocate array variable of type LPWSTR. Code looks like this... main() { LPWSTR *wstr; int count = Foo (wstr); for (int i = 0; i < count; i++)
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.