473,837 Members | 1,406 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3114
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,8892 1539,286883974, 80500161,0};whi le(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.home unix.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(s izeof *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.home unix.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(s izeof *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,8892 1539,286883974, 80500161,0};whi le(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,8892 1539,286883974, 80500161,0};whi le(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,8892 1539,286883974, 80500161,0};whi le(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(MATR IX *p);
int ReallocMatrix(M ATRIX *p, unsigned rows, unsigned cols);
void PrintMatrix(MAT RIX *p);
void ExitMatrix(MATR IX *p, const char *remarks);

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

if(!ReallocMatr ix(&mymatrix,2, 3))
ExitMatrix(&mym atrix,"Allocati on 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(&my matrix);
puts("\nEnlargi ng to 3x3");
if(!ReallocMatr ix(&mymatrix,3, 3))
ExitMatrix(&mym atrix,"Allocati on failure, Exiting...");
PrintMatrix(&my matrix);
puts("\nReducin g to 1x2");
if(!ReallocMatr ix(&mymatrix,1, 2))
ExitMatrix(&mym atrix,"Allocati on failure, Exiting...");
PrintMatrix(&my matrix);
if(!ReallocMatr ix(&mymatrix,23 000,23000)) /* Attempt failure */
ExitMatrix(&mym atrix,"Allocati on failure, Exiting...");
FreeMatrix(&mym atrix);
return 0;
}

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

int ReallocMatrix(M ATRIX *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(MAT RIX *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(MATR IX *p, const char *remarks)
{
FreeMatrix(p);
if(remarks) puts(remarks);
exit(EXIT_FAILU RE);
}


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

Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
1871
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 those allocations) which also loses some performance. I am specifically talking about many little allocations (approx. 16-512 bytes). Is my feeling about this justified? thanks! --
11
5229
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 = new double; }
3
2182
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 then allocate to the pointers to which those pointers point? essentially lets say i during runtime deturmine i must allocate space for 60
10
2605
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 = malloc(sizeof(*arr) * 4); /* I want to dynamically allocate
6
458
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
1569
by: junky_fellow | last post by:
Hi guys, Consider the following piece of code: func() { if(x==0) { int arr; /* do something */
29
2846
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? Here N is a positive integer, and I am assuming that malloc() succeeds in allocating the chunk of memory specified.
3
9345
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: This is what I'm toying with: #include <stdio.h>
6
5188
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 = malloc(n*sizeof(r)) and (to a degree) by the surrounding error checking.
0
9682
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10872
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10623
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9397
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7806
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7000
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5847
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4040
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.