Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   malloc a 2D array (http://www.velocityreviews.com/forums/t315202-malloc-a-2d-array.html)

mike79 09-10-2003 11:56 PM

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

Tom Zych 09-11-2003 01:23 AM

Re: malloc a 2D array
 
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 'gbzmlpu@cbobk.pbz' | rot13

Kevin Easton 09-11-2003 01:30 AM

Re: malloc a 2D array
 
mike79 <mike79@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.


pete 09-11-2003 01:32 AM

Re: malloc a 2D array
 
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 */

Tom Zych 09-11-2003 01:45 AM

Re: malloc a 2D array
 
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 'gbzmlpu@cbobk.pbz' | rot13

Tom Zych 09-11-2003 01:46 AM

Re: malloc a 2D array
 
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 'gbzmlpu@cbobk.pbz' | rot13

pete 09-11-2003 02:54 AM

Re: malloc a 2D array
 
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

vincetg2 01-23-2009 07:23 PM

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);


isezen 05-14-2009 08:02 AM

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
}


WhatIThink 02-25-2011 06:53 AM

Quote:

Originally Posted by vincetg2 (Post 3777839)
Code:

if(NULL == matrix){free(matrix);

what's the point of freeing a pointer if you already know it's null


All times are GMT. The time now is 10:56 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.