473,228 Members | 1,755 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,228 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 3059
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Jakob Bieling | last post by:
Hi, Whenever allocating memory using operator new or operator new I feel like I should only use it very sparingly, because otherwise memory is wasted (by additional overhead needed to manage all...
11
by: fivelitermustang | last post by:
Actually, how would I go about allocating a four-dimensional dynamic array? I only know how to make two dimensional dynamic arrays: double **v; v = new double*; for (int i=0; i<C; i++) { v =...
3
by: Erik S. Bartul | last post by:
lets say i want to fill up a multidimentional array, but i wish to allocate memory for it on the fly. i assume i declare, char **a; but how do i allocate memory for the pointers, so i can...
10
by: junky_fellow | last post by:
What is the correct way of dynamically allocating a 2d array ? I am doing it the following way. Is this correct ? #include <stdlib.h> int main(void) { int (*arr)(3); arr =...
6
by: Paminu | last post by:
If I have this struct: #include <stdlib.h> #include <stdio.h> #define KIDS 4 typedef struct test { int x; int y; } container;
16
by: junky_fellow | last post by:
Hi guys, Consider the following piece of code: func() { if(x==0) { int arr; /* do something */
29
by: K. Jennings | last post by:
I would like to get the result of malloc() such that it is aligned on a given boundary - 8, in this case. Assuming that sizeof(u64) is 8, will u64 *p = malloc(N) ; do the trick in general? ...
3
by: UncleRic | last post by:
Greetings: I'm trying to get the ASCI C syntax correct here. I want to create memory space for a variable-size array of pointers to structs. This is what I found in theScripts' archive: ...
6
by: Francois Grieu | last post by:
Hello, I'm asking myself all kind of questions on allocating an array of struct with proper alignment. Is the following code oorrect ? I'm most interested by the statement t =...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.