473,698 Members | 2,942 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2573
ju**********@ya hoo.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**********@ya hoo.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*******@free net.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**********@ya hoo.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.c om> 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_Keit h) 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**********@ya hoo.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**********@ya hoo.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

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

Similar topics

14
3544
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 sort of dynamically allocated array of : (1) void pointers, that must be cast into the desired types. (2) union of the desired pointers. (3) An Inheritance hierarchy (4) Possibly a union of the desired data types.
5
2369
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
3105
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. Unfortunately, this segfaults. The output is the following: $ gcc -Wall -c arrays.c $ gcc -o arrays arrays.o $ ./arrays
7
3126
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: /* Allocate 1st dimension */ if((Screen = (Atom ***) malloc(sizeof(Atom **) * Width)) == NULL) perrexit("malloc");
3
1844
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 considered as pixel colours and the size that 1 pixel occupies will depend on an input from the user when running the program. How can I dynamically change the data type of my 3D array at runtime. eg. 3D array was defined as type unsigned char in the code...
94
4729
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 that I found inside of a string. Any ideas?
6
2623
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 use these in a linked list for something else I am working on, but I want to make sure my understanding of the concept is correct. For example, from the code below string would equal 'h' after
3
6898
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 element;
28
7145
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
8683
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8611
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8904
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8876
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.