Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > malloc a 2D array

Reply
Thread Tools

malloc a 2D array

 
 
mike79
Guest
Posts: n/a
 
      09-10-2003
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
 
Reply With Quote
 
 
 
 
Tom Zych
Guest
Posts: n/a
 
      09-11-2003
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 '(E-Mail Removed)' | rot13
 
Reply With Quote
 
 
 
 
Kevin Easton
Guest
Posts: n/a
 
      09-11-2003
mike79 <(E-Mail Removed)> 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.

 
Reply With Quote
 
pete
Guest
Posts: n/a
 
      09-11-2003
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 */
 
Reply With Quote
 
Tom Zych
Guest
Posts: n/a
 
      09-11-2003
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 '(E-Mail Removed)' | rot13
 
Reply With Quote
 
Tom Zych
Guest
Posts: n/a
 
      09-11-2003
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 '(E-Mail Removed)' | rot13
 
Reply With Quote
 
pete
Guest
Posts: n/a
 
      09-11-2003
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
 
Reply With Quote
 
vincetg2 vincetg2 is offline
Junior Member
Join Date: Jan 2009
Posts: 1
 
      01-23-2009
Here's how you dynamically allocate memory for a 2D array.
Presented in matrix[col][row] format:
Iterating through its columns moves in the x direction.
Iterating through its rows moves in the y direction.

Code:
/* Written by Vincent Garcia::Undergrad::UCSB.*/


/* This is your 2D array. */
double** matrix;
/* The size dimensions of your 2D array. */
int numRows, numCols;
/* Used as indexes as in matrix[x][y]; */
int x, y; 
/*
 * Get values into numRows and numCols somehow.
 */


/* Allocate pointer memory for the first dimension of a matrix[][]; */
matrix = (double **) malloc(numCols * sizeof(double *));
if(NULL == matrix){free(matrix); printf("Memory allocation failed while allocating for matrix[].\n"); exit(-1);}

/* Allocate integer memory for the second dimension of a matrix[][]; */
for(x = 0; x < numCols; x++)
{
    matrix[x] = (double *) malloc(numRows * sizeof(double));
    if(NULL == matrix[x]){free(matrix[x]); printf("Memory allocation failed while allocating for matrix[x][].\n"); exit(-1);}
}


/* Iterate through matrix (thru-row-first). */
/* Initialize matrix to be filled with 0's. */
for(y = 0; y < numRows; i++)
    for(x = 0; x < numCols; j++)
        matrix[x][y] = 0;


/* Deallocate memory of 2D array. */
for(x = 0; x < numCols; x++)
    free(matrix[x]);
free(matrix);
 
Reply With Quote
 
isezen isezen is offline
Junior Member
Join Date: May 2009
Posts: 1
 
      05-14-2009
Thank you very much vincetg2 for the clear solution. It was quite usefull for me. I modified your code a little bit, perhaps this will be usefull for another one. I'm not a C expert,So if you have any sugegestions about the code, please post a reply. I think, this is the right way to create a 2D array by a function. It seems to work for me, but perhaps I overlooked something? Thanks again for the snippet, anyway.

Code:
char** create_2D_char_array( int numrows, int numcols){
	char **data;
	data = (char **) malloc(numrows * sizeof(char *));
	if(data == NULL){
		free(data);
		printf("Memory allocation failed while allocating for dim[].\n");
		exit(-1);
	}
	//
	/* Allocate integer memory for the second dimension of a dim[][]; */
	register int i;
	for(i = 0; i < numrows; i++) {
		data[i] = (char *) malloc(numcols * sizeof(char));
		if(NULL == data[i]){
			free(data[i]);
			printf("Memory allocation failed while allocating for dim[x][].\n");
			exit(-1);
		}
	}
	return *&data; // Success
}
 
Reply With Quote
 
WhatIThink WhatIThink is offline
Junior Member
Join Date: Dec 2008
Posts: 14
 
      02-25-2011
Quote:
Originally Posted by vincetg2 View Post
Code:
if(NULL == matrix){free(matrix);
what's the point of freeing a pointer if you already know it's null
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
to malloc or not to malloc?? Johs32 C Programming 4 03-30-2006 10:03 AM
porting non-malloc code to malloc micromysore@gmail.com C Programming 3 02-19-2005 05:39 AM
Malloc/Free - freeing memory allocated by malloc Peter C Programming 34 10-22-2004 10:23 AM
free'ing malloc'd structure with malloc'd members John C Programming 13 08-02-2004 11:45 AM
Re: free'ing malloc'd structure with malloc'd members ravi C Programming 0 07-30-2004 12:42 PM



Advertisments