Reputation: 1533
I am trying to represent a matrix as an array of pointers, and then do certain actions on the matrix.
To simplify further, imagine a matrix with n
rows and m
columns,
I defined an int **matrix
that points to the beginning of an array (of pointers) of size n
. And every block in this array is a pointer that points to an array (of integers) of size m
. The result is clear. you have n
pointers, each of them pointing to an array of m
integers, overall nxm
values. So it should be possible to represent a matrix this way.
My problem is that I don't know how to access the integer values of the matrix. For example, suppose I wish to insert values to the matrix. How do I access matrix[i][j]
?
Here is my code, you can see it is incomplete, I would appreciate help completing it.
int** create_matrix(int rows,int columns)
{
int** matrix,i;
matrix=(int**)malloc(rows*sizeof(int*));
for(i=0;i<rows;i++)
*(matrix)+i=(int*)malloc(columns*sizeof(int));
for(i=0;i<rows;i++)
{
for(j=0;j<columns;j++)
*(*(matrix)+i)
I want to insert random numbers into the matrix and then return it. I allocated the necesary memory, just need to insert the actual values.
Upvotes: 0
Views: 1586
Reputation: 3870
Try the following code-
int** create_matrix(int rows,int columns)
{
int** matrix,i;
matrix=(int**)malloc(rows*sizeof(int*));
for(i=0;i<rows;i++)
matrix[i]=(int*)malloc(columns*sizeof(int)); // Fix 1
for(i=0;i<rows;i++)
{
for(j=0;j<columns;j++)
*(*(matrix+i)+j)=rand();
}
return matrix;
}
Instead of doing arithmetic you can directly access it by matrix[i][j]
. matrix[i][j]
is equal to *(*(matrix+i)+j)
.
Upvotes: 1
Reputation: 9814
int** matrix,i,j;
matrix=malloc(rows*sizeof(int*));
for(i=0;i<rows;i++)
*(matrix+i)=malloc(columns*sizeof(int)); //or matrix[i]=malloc(columns*sizeof(int));
for(i=0;i<rows;i++)
{
for(j=0;j<columns;j++)
*(*(matrix+i)+j)=random(); //or matrix[i][j]=random();
}
return matrix;
Note the change of the parentheses around matrix
Upvotes: 1
Reputation: 123598
The general pattern for any type T
is
T **arr = malloc( rows * sizeof *arr );
if ( arr )
{
for ( size_t i = 0; i < rows; i++ )
{
arr[i] = malloc( columns * sizeof *arr[i] );
if ( arr[i] )
{
for ( size_t j = 0; j < columns; j++ )
{
arr[i][j] = some_value;
}
}
else
// memory allocation failure
}
}
else
// memory allocation failure.
Array subscripts are defined in terms of pointer arithmetic: a[i]
is defined as *(a + i)
. a[i][j]
is defined as *(*(a + i) + j)
.
Upvotes: 1