473,399 Members | 3,656 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,399 software developers and data experts.

malloc a 2D array

Hey all,

Im use to using malloc() with a one-dimensional array. But I have
found the need to use a 2D array, and would like to confirm whether I
am allocating memory correctly.

As I can gather, unlike a 1D array, you cannot allocate memory to a 2D
array with only 1 line of code.

Just say i wish to have an array of strings, I wish to declare an
array like arrayString[10][20], where I will be able to hold 10
strings, each string of a maximum of 20 characters (as an example).

Can I do this?

************************************
arrayString = malloc(10);

int i;
for (i = 0; i< 10; i++)
{
arrayString[i] = malloc(20);
}
************************************

Would this be ideal, or is there a better solution to this problem?

Thank you all for your help.. Much appreciated!
mike79
Nov 13 '05 #1
6 20704
mike79 wrote:
Im use to using malloc() with a one-dimensional array. But I have
found the need to use a 2D array, and would like to confirm whether I
am allocating memory correctly. As I can gather, unlike a 1D array, you cannot allocate memory to a 2D
array with only 1 line of code.
Depends how you do it.
Just say i wish to have an array of strings, I wish to declare an
array like arrayString[10][20], where I will be able to hold 10
strings, each string of a maximum of 20 characters (as an example).
For consistency with your code I will assume you mean 19 characters
plus the terminating \0.
Can I do this? ************************************
arrayString = malloc(10);

int i;
for (i = 0; i< 10; i++)
{
arrayString[i] = malloc(20);
}
************************************
arrayString is an array of pointers to char. Hence:
char **arrayString;
arrayString = malloc(10 * sizeof (char *));

Usual caveats about checking the return value from malloc apply.

This way requires a loop to allocate, but allows the usual
arrayString[i][j] usage.
Would this be ideal, or is there a better solution to this problem?


If you want to avoid the loop, you can just make arrayString a
pointer to char, malloc(10*20), and do pointer arithmetic. I'd say
the loop is easier all around.

--
Tom Zych
This email address will expire at some point to thwart spammers.
Permanent address: echo 'g******@cbobk.pbz' | rot13
Nov 13 '05 #2
mike79 <mi****@iprimus.com.au> wrote:
Hey all,

Im use to using malloc() with a one-dimensional array. But I have
found the need to use a 2D array, and would like to confirm whether I
am allocating memory correctly.

As I can gather, unlike a 1D array, you cannot allocate memory to a 2D
array with only 1 line of code.

Just say i wish to have an array of strings, I wish to declare an
array like arrayString[10][20], where I will be able to hold 10
strings, each string of a maximum of 20 characters (as an example).

Can I do this?

************************************
arrayString = malloc(10);
Nope. arrayString should be declared as:

char **arrayString;

and so your malloc is allocating space for 10 (char *)s, not 10 chars:

arrayString = malloc(10 * sizeof *arrayString);
int i;
for (i = 0; i< 10; i++)
{
arrayString[i] = malloc(20);
}
************************************

Would this be ideal, or is there a better solution to this problem?


If the size of strings is known at compile-time, and you aren't going to
be swapping strings around inside the array, this is probably better:

char (*arrayString)[20];

arrayString = malloc(10 * sizeof *arrayString);

.... that's it.

There are some more methods in the comp.lang.c FAQ.

- Kevin.

Nov 13 '05 #3
mike79 wrote:

Hey all,

Im use to using malloc() with a one-dimensional array. But I have
found the need to use a 2D array, and would like to confirm whether I
am allocating memory correctly.

As I can gather, unlike a 1D array, you cannot allocate memory to a 2D
array with only 1 line of code.

Just say i wish to have an array of strings, I wish to declare an
array like arrayString[10][20], where I will be able to hold 10
strings, each string of a maximum of 20 characters (as an example).


/*
** Make a pointer to the first element of the two dimensional array:
** char (*arrayString_ptr)[20];
** arrayString_ptr = malloc(10 * sizeof *arrayString_ptr);
*/

/* BEGIN new.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
char *number[] = {"one","two","three","four","five","six",
"seven","eight","nine","ten"};
char (*arrayString_ptr)[20];
int word;

arrayString_ptr = malloc(10 * sizeof *arrayString_ptr);
if (!arrayString_ptr) {
fputs("I'm tired.\n", stderr);
exit(EXIT_FAILURE);
}
for (word = 0; word != 10; ++word) {
strcpy(arrayString_ptr[word], number[word]);
}
for (word = 0; word != 10; ++word) {
puts(arrayString_ptr[word]);
}
free(arrayString_ptr);
return 0;
}

/* END new.c */
Nov 13 '05 #4
Kevin Easton wrote:
arrayString = malloc(10 * sizeof *arrayString);
Whoops, my bad. I knew better, too. Do it this way, not the way I
wrote it.
If the size of strings is known at compile-time, and you aren't going to
be swapping strings around inside the array, this is probably better: char (*arrayString)[20]; arrayString = malloc(10 * sizeof *arrayString);


Perhaps it's just unfamiliarity, but I find this hard to understand.
I think the malloc-twice way is much more intuitive. Opinions?

--
Tom Zych
This email address will expire at some point to thwart spammers.
Permanent address: echo 'g******@cbobk.pbz' | rot13
Nov 13 '05 #5
pete wrote:
char *number[] = {"one","two","three","four","five","six",
"seven","eight","nine","ten"};


A C programmer who starts counting at one. How unusual... :)

--
Tom Zych
This email address will expire at some point to thwart spammers.
Permanent address: echo 'g******@cbobk.pbz' | rot13
Nov 13 '05 #6
Tom Zych wrote:

Kevin Easton wrote:

char (*arrayString)[20];

arrayString = malloc(10 * sizeof *arrayString);


Perhaps it's just unfamiliarity, but I find this hard to understand.
I think the malloc-twice way is much more intuitive. Opinions?


it's just unfamiliarity
Nov 13 '05 #7

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

Similar topics

14
by: dam_fool_2003 | last post by:
Friends, cannot we malloc a array? So, I tried the following code: int main(void) { unsigned int y={1,3,6},i,j; for(i=0;i<3;i++) printf("before =%d\n",y); *y = 7; /* 1*/
6
by: Vamsee | last post by:
I have a 4D array: float T; ( have to go atleast upto T if system supports) How to malloc() it? can you please give me a brief illustration because I haven't found any article dealing with...
10
by: Ian Todd | last post by:
Hi, I am trying to read in a list of data from a file. Each line has a string in its first column. This is what i want to read. I could start by saying char to read in 1000 lines to the array( i...
7
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ...
36
by: Martin Andert | last post by:
Hello, I have a question regarding malloc and free. Here my code sample: int main() { /* allocating dynamic memory for array */ int* array = (int*) malloc(5 * sizeof(int)); /* ... program...
20
by: spasmous | last post by:
main() { float * f; initialize_f(f); // ...use f for processing free(f); }
15
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that...
24
by: VijaKhara | last post by:
hi all, i am trying to create a dynamic 2D array with size N x 3 (N will be put in as a parameter) using the following code: int **xyz; int i,N; N=30000; xyz=malloc(3*sizeof(int*));
23
by: raphfrk | last post by:
I am having an issue with malloc and gcc. Is there something wrong with my code or is this a compiler bug ? I am running this program: #include <stdio.h> #include <stdlib.h> typedef...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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...

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.