473,803 Members | 3,463 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
10 2598
On 12 Sep 2005 03:56:48 -0700, "John Bode" <jo*******@my-deja.com>
wrote:
ju**********@y ahoo.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
3552
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
2373
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
3112
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
3128
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
1850
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
4788
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
2631
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
6905
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
7169
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
9703
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
10548
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10295
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
10069
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
7604
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
6842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5500
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...
2
3798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
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.