allocating space for an array of integers

G

Gattaca

I would like to create a matrix[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
 
C

Case

Gattaca said:
I would like to create a matrix[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
 
P

Pieter Droogendijk

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.
 
R

Richard Bos

Pieter Droogendijk said:
Not in my book.

Nor in mine, but not entirely for the reasons you mention.
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
 
P

Pieter Droogendijk

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.
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
 
C

Case

Pieter said:
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
 
P

Pieter Droogendijk

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.
 
C

Case

Pieter said:
No worries ;)




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
 
A

Al Bowers

Gattaca said:
I would like to create a matrix[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[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 = tmp[0] + i * cols;
for(j = 0;j < cols;j++)
if(i < p->row && j < p->col)
tmp[j] = p->matrix[j];
else tmp[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[j]);
putchar('\n');
}
putchar('\n');
return;
}

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

Richard Bos

Case said:
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
 
C

Case

Richard said:
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
 
C

Case

Richard said:
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!
 
D

Default User

Case said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top