471,108 Members | 1,595 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,108 software developers and data experts.

allocating space for an array of integers

I would like to create a matrix[i][j] of integers by allocating memory
dynamically (malloc or calloc) because i and j are defined during
execution of the program.

I have got not problem to do this in the static way. For instance, if I
want to declare a matrix 20x10 of integers and then to access
matrix[15,8] element:
int matrix[20][10];
int a;

a=matrix[15][8];

But I havn't the clue to do it dynamically in case of i=20 and j=10.
int i,j,a;
i=20;j=10;

Thanks for your help,

Gattaca
Nov 14 '05 #1
14 2866
Gattaca wrote:
I would like to create a matrix[i][j] of integers by allocating memory
dynamically (malloc or calloc) because i and j are defined during
execution of the program.

I have got not problem to do this in the static way. For instance, if I
want to declare a matrix 20x10 of integers and then to access
matrix[15,8] element:
int matrix[20][10];
int a;

a=matrix[15][8];

But I havn't the clue to do it dynamically in case of i=20 and j=10.
int i,j,a;
i=20;j=10;


That would be:

int **matrix;

matrix = (int **)calloc(i * j, sizeof int);

a = matrix[15][8];

The C-FAQ, K&R and many other sources give more details
about other ways to this and other things related to multi-
dimentional arrays.

Case

Nov 14 '05 #2
On Mon, 24 May 2004 12:41:57 +0200, Case wrote:
That would be:
Not in my book.
int **matrix;

matrix = (int **)calloc(i * j, sizeof int);
Besides the fact that you shouldn't cast here, and that sizeof int is a
syntax error (you must mean sizeof (int)), this allocates a continuous
block of memory i*j*sizeof(int) long, all pointers to pointers to int.
a = matrix[15][8];
matrix[15] may exist, but it's NULL.

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

int main (void)
{
int i=20, j=10;
int count;
int **matrix;
matrix = malloc (sizeof*matrix*i);
if (matrix == NULL)
return EXIT_FAILURE;
for (count=0; count < i; count++) {
matrix[count] = malloc (sizeof*matrix[count]*j);
if (matrix[count] == NULL)
return EXIT_FAILURE;
}
matrix[15][8] = 10;
printf ("%d\n", matrix[15][8]);

for (count=0; count < i; count++)
free (matrix[count]);
free (matrix);
return 0;
}
The C-FAQ, K&R and many other sources give more details
about other ways to this and other things related to multi-
dimentional arrays.


Indeed.

--
int main(void){int putchar(int),i=0;unsigned long t=500555079,n[]={t
,159418370,88921539,286883974,80500161,0};while(n[i])putchar(*(!(t&1
)+!(t||!++i)+"# \n")),(t&&1+(t>>=i-~-i))||(t=n[i]^n[i-1]);return 0;}

Nov 14 '05 #3
Pieter Droogendijk <gi*@binky.homeunix.org> wrote:
On Mon, 24 May 2004 12:41:57 +0200, Case wrote:
That would be:
Not in my book.


Nor in mine, but not entirely for the reasons you mention.
int **matrix;

matrix = (int **)calloc(i * j, sizeof int);


Besides the fact that you shouldn't cast here, and that sizeof int is a
syntax error (you must mean sizeof (int)), this allocates a continuous
block of memory i*j*sizeof(int) long, all pointers to pointers to int.


You were right up to the size of the block, but where do you get the
impression that a just allocated block of memory has a type of "all
pointers to pointers to int"? It's bytes, and how those bytes are
interpreted depends on the pointer you use to access it.
In this case, matrix is an int **. That means that *matrix is seen as an
int *, not as an int **. You could just as easily have assigned the
result of the calloc() call to an unsigned char *, and treated all bytes
as unsigned chars.
a = matrix[15][8];


matrix[15] may exist, but it's NULL.


No - it's all bits zero, which is not necessarily the same thing. This
is one reason why calloc() is less useful than malloc() - you can't
reliably use it for anything but integer types. For pointers and
floating point types, all bits zero is not necessarily an interesting
value.
#include <stdlib.h>
#include <stdio.h>

int main (void)
{
int i=20, j=10;
int count;
int **matrix;
matrix = malloc (sizeof*matrix*i);


Rather obfuscatory use of whitespace there, I think. It'd be clearer as

matrix=malloc(sizeof *matrix * i);

or even better

matrix=malloc(i * sizeof *matrix);

No more comments on your code, except that in a non-toy program, you
need to be more careful about what happens on malloc() error.

Richard
Nov 14 '05 #4
On Mon, 24 May 2004 11:17:38 +0000, Richard Bos wrote:
7> Pieter Droogendijk <gi*@binky.homeunix.org> wrote:
On Mon, 24 May 2004 12:41:57 +0200, Case wrote:
You were right up to the size of the block, but where do you get the
impression that a just allocated block of memory has a type of "all
pointers to pointers to int"? It's bytes, and how those bytes are
interpreted depends on the pointer you use to access it.
Pardon the odd wording. I was indeed referring to the way the memory just
allocated is going to be used.
matrix[15] may exist, but it's NULL.


No - it's all bits zero, which is not necessarily the same thing. This
is one reason why calloc() is less useful than malloc() - you can't
reliably use it for anything but integer types. For pointers and
floating point types, all bits zero is not necessarily an interesting
value.


Agreed. This hit me after pressing send, regrettably.
matrix = malloc (sizeof*matrix*i);


Rather obfuscatory use of whitespace there, I think. It'd be clearer as

matrix=malloc(sizeof *matrix * i);

or even better

matrix=malloc(i * sizeof *matrix);


Agreed as well, heh. Bad habit.
No more comments on your code, except that in a non-toy program, you
need to be more careful about what happens on malloc() error.


Naturally. But since this is not a non-toy program... :P

--
int main(void){int putchar(int),i=0;unsigned long t=500555079,n[]={t
,159418370,88921539,286883974,80500161,0};while(n[i])putchar(*(!(t&1
)+!(t||!++i)+"# \n")),(t&&1+(t>>=i-~-i))||(t=n[i]^n[i-1]);return 0;}

Nov 14 '05 #5
Pieter Droogendijk wrote:
On Mon, 24 May 2004 12:41:57 +0200, Case wrote:
That would be:

Not in my book.
int **matrix;

matrix = (int **)calloc(i * j, sizeof int);

Besides the fact that you shouldn't cast here, and that sizeof int is a
syntax error (you must mean sizeof (int)), this allocates a continuous
block of memory i*j*sizeof(int) long, all pointers to pointers to int.


You are right! I acted as if answering this question was a no-brainer
and seemingly it's been too long ago I worked with MD arrays or read the
FAQ.

BTW, the FAQ (Q6.16) does use a cast:

int **array1 = (int **)malloc(nrows * sizeof(int *));

Why do you think there should be none?

I'll think a bit longer next time when I answer a question right before
running off for lunch. Oops.

Case

Nov 14 '05 #6
On Mon, 24 May 2004 13:33:50 +0200, Case wrote:
Pieter Droogendijk wrote:
On Mon, 24 May 2004 12:41:57 +0200, Case wrote:
You are right! I acted as if answering this question was a no-brainer
and seemingly it's been too long ago I worked with MD arrays or read the
FAQ.
No worries ;)
BTW, the FAQ (Q6.16) does use a cast:

int **array1 = (int **)malloc(nrows * sizeof(int *));

Why do you think there should be none?


Because it may mask undefined behaviour if you forget to include stdlib.h.
If that's the case, malloc() will be implicitly declared to return int,
but you tell your compiler "No, it's (int**), I know what I'm doing better
than you", so even if it was going to produce a diagnostic, it won't.

--
int main(void){int putchar(int),i=0;unsigned long t=500555079,n[]={t
,159418370,88921539,286883974,80500161,0};while(n[i])putchar(*(!(t&1
)+!(t||!++i)+"# \n")),(t&&1+(t>>=i-~-i))||(t=n[i]^n[i-1]);return 0;}

Nov 14 '05 #7
Pieter Droogendijk wrote:
On Mon, 24 May 2004 13:33:50 +0200, Case wrote:

Pieter Droogendijk wrote:
On Mon, 24 May 2004 12:41:57 +0200, Case wrote:


You are right! I acted as if answering this question was a no-brainer
and seemingly it's been too long ago I worked with MD arrays or read the
FAQ.

No worries ;)

BTW, the FAQ (Q6.16) does use a cast:

int **array1 = (int **)malloc(nrows * sizeof(int *));

Why do you think there should be none?

Because it may mask undefined behaviour if you forget to include stdlib.h.
If that's the case, malloc() will be implicitly declared to return int,
but you tell your compiler "No, it's (int**), I know what I'm doing better
than you", so even if it was going to produce a diagnostic, it won't.


Good point. Any ideas why the FAQ still uses a cast?

Kees

Nov 14 '05 #8
On Mon, 24 May 2004 13:45:25 +0200, Case wrote:
Pieter Droogendijk wrote: Good point. Any ideas why the FAQ still uses a cast?


Good question, and not one I can answer.

--
int main(void){int putchar(int),i=0;unsigned long t=500555079,n[]={t
,159418370,88921539,286883974,80500161,0};while(n[i])putchar(*(!(t&1
)+!(t||!++i)+"# \n")),(t&&1+(t>>=i-~-i))||(t=n[i]^n[i-1]);return 0;}

Nov 14 '05 #9


Gattaca wrote:
I would like to create a matrix[i][j] of integers by allocating memory
dynamically (malloc or calloc) because i and j are defined during
execution of the program.

I have got not problem to do this in the static way. For instance, if I
want to declare a matrix 20x10 of integers and then to access
matrix[15,8] element:
int matrix[20][10];
int a;

a=matrix[15][8];

But I havn't the clue to do it dynamically in case of i=20 and j=10.
int i,j,a;
i=20;j=10;


I take that you want to dymanically allocate a matrix and then
possibly later in the program modify the dimensions. Do do this
you can use one of the 2d allocation routines mentioned in the
faq. On reallocation, I presume you want to keep all the values
in the previous allocation that are possible. I would create
a struct datatype that has as members, pointer to the matrix array,
size of the columns and size of the rows. Write functions to
manipulate this datatype.

Example (untested)

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

typedef struct MATRIX
{
int **matrix;
unsigned row;
unsigned col;
} MATRIX;

void FreeMatrix(MATRIX *p);
int ReallocMatrix(MATRIX *p, unsigned rows, unsigned cols);
void PrintMatrix(MATRIX *p);
void ExitMatrix(MATRIX *p, const char *remarks);

int main(void)
{
MATRIX mymatrix = {NULL};
unsigned i, j;

if(!ReallocMatrix(&mymatrix,2,3))
ExitMatrix(&mymatrix,"Allocation failure, Exiting...");
for(i = 0; i < mymatrix.row;i++)
for(j = 0; j < mymatrix.col; j++)
mymatrix.matrix[i][j] = i+j*10;
puts("Matrix 2x3");
PrintMatrix(&mymatrix);
puts("\nEnlarging to 3x3");
if(!ReallocMatrix(&mymatrix,3,3))
ExitMatrix(&mymatrix,"Allocation failure, Exiting...");
PrintMatrix(&mymatrix);
puts("\nReducing to 1x2");
if(!ReallocMatrix(&mymatrix,1,2))
ExitMatrix(&mymatrix,"Allocation failure, Exiting...");
PrintMatrix(&mymatrix);
if(!ReallocMatrix(&mymatrix,23000,23000)) /* Attempt failure */
ExitMatrix(&mymatrix,"Allocation failure, Exiting...");
FreeMatrix(&mymatrix);
return 0;
}

void FreeMatrix(MATRIX *p)
{
free(p->matrix[0]);
free(p->matrix);
p->matrix = NULL;
p->row = p->col = 0;
return;
}

int ReallocMatrix(MATRIX *p, unsigned rows, unsigned cols)
{
int **tmp;
unsigned i,j;

if(p == NULL || rows == 0 || cols == 0) return 0;
if((tmp = malloc(rows * (sizeof *tmp))) == NULL) return 0;
if((tmp[0] = malloc(rows * cols * (sizeof **tmp))) == NULL)
{
free(tmp);
return 0;
}
for(i = 0; i < rows; i++)
{
tmp[i] = tmp[0] + i * cols;
for(j = 0;j < cols;j++)
if(i < p->row && j < p->col)
tmp[i][j] = p->matrix[i][j];
else tmp[i][j] = 0;
}
free(p->matrix);
p->matrix = tmp;
p->row = rows;
p->col = cols;
return 1;
}

void PrintMatrix(MATRIX *p)
{
unsigned i,j;

for(i = 0;i < p->row;i++)
{
for(j = 0; j < p->col;j++)
printf("%-4d",p->matrix[i][j]);
putchar('\n');
}
putchar('\n');
return;
}

void ExitMatrix(MATRIX *p, const char *remarks)
{
FreeMatrix(p);
if(remarks) puts(remarks);
exit(EXIT_FAILURE);
}


--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #10
Case <no@no.no> wrote:
BTW, the FAQ (Q6.16) does use a cast:

int **array1 = (int **)malloc(nrows * sizeof(int *));

Why do you think there should be none?


For several reasons. There have been near endless threads about this on
c.l.c over the past years. I'm sure you can find some of them in a
Usenet archive. Let me just present my favourite argument: by adding a
cast to malloc(), which does not need it at all and is pretty common in
C code, you train yourself to think "Oh, yet another cast. Yawn." Then,
when you encounter a _real_ cast, in a situation where it is needed, you
do not, as you should, sit up and pay attention, because something odd
is done to the C type system; you are used to casts doing, in essence,
nothing, when you _should_ consider a cast to be a warning sign. IOW, a
programmer who casts malloc() is like the little boy who cried "Wolf!".

Richard
Nov 14 '05 #11
Richard Bos wrote:
Case <no@no.no> wrote:

BTW, the FAQ (Q6.16) does use a cast:

int **array1 = (int **)malloc(nrows * sizeof(int *));

Why do you think there should be none?

For several reasons. There have been near endless threads about this on
c.l.c over the past years. I'm sure you can find some of them in a
Usenet archive. Let me just present my favourite argument: by adding a
cast to malloc(), which does not need it at all and is pretty common in
C code, you train yourself to think "Oh, yet another cast. Yawn." Then,
when you encounter a _real_ cast, in a situation where it is needed, you
do not, as you should, sit up and pay attention, because something odd
is done to the C type system; you are used to casts doing, in essence,
nothing, when you _should_ consider a cast to be a warning sign. IOW, a
programmer who casts malloc() is like the little boy who cried "Wolf!".


I never knew that K&R are both little boys. ;-) I see malloc() casts
all over their famous book. At page 167 they even say:

"The pointer returned by malloc or calloc has the proper
alignment for the object in question, but it *must* be
cast into the appropriate type, as in ..."

Why the heck is this? And was the FAQ written by other little boys?

Case

Nov 14 '05 #12
Richard Bos wrote:
Case <no@no.no> wrote:

BTW, the FAQ (Q6.16) does use a cast:

int **array1 = (int **)malloc(nrows * sizeof(int *));

Why do you think there should be none?

For several reasons. There have been near endless threads about this on
c.l.c over the past years. I'm sure you can find some of them in a
Usenet archive.


I'll try to find some later. Thanks!

Nov 14 '05 #13
Case wrote:
I never knew that K&R are both little boys. ;-) I see malloc() casts
all over their famous book. At page 167 they even say:

"The pointer returned by malloc or calloc has the proper
alignment for the object in question, but it *must* be
cast into the appropriate type, as in ..."

From Ritchie's on-line errata list:
142(6.5, toward the end): The remark about casting the return value of
malloc ("the proper method is to declare ... then explicitly coerce")
needs to be rewritten. The example is correct and works, but the advice
is debatable in the context of the 1988-1989 ANSI/ISO standards. It's
not necessary (given that coercion of void * to ALMOSTANYTYPE * is
automatic), and possibly harmful if malloc, or a proxy for it, fails to
be declared as returning void *. The explicit cast can cover up an
unintended error. On the other hand, pre-ANSI, the cast was necessary,
and it is in C++ also.

http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html


Brian Rodenborn
Nov 14 '05 #14
On Mon, 24 May 2004 13:33:50 +0200, Case <no@no.no> wrote:
<snipped casting (return from) malloc>
BTW, the FAQ (Q6.16) does use a cast:

Not in the latest version, ca 1999 (!), which the web version at
http://www.eskimo.com/~scs/C-faq/top.html (still!) is NOT.

See the download/plaintext versions there under versions.html,
periodically posted, and at rtfm.mit.edu and faqs.org.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #15

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Jakob Bieling | last post: by
11 posts views Thread by fivelitermustang | last post: by
3 posts views Thread by Erik S. Bartul | last post: by
10 posts views Thread by junky_fellow | last post: by
6 posts views Thread by Paminu | last post: by
16 posts views Thread by junky_fellow | last post: by
29 posts views Thread by K. Jennings | last post: by
6 posts views Thread by Francois Grieu | last post: by

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.