Allocation of 2D arrays (matrices) in C? - c

I am working on C, specifically on creating a matrix using pointers, and one thing that confuses me is that in a 2D array that matrix[i][j] is equal to
*(*(matrix+i)+j)
Does this mean that the element located, in say, the position [3][3] is given by *(*(0+3)+3))?
More specifically, I'm coding a matrix in C by using the following code:
double** makeMatrix(unsigned int rows, unsigned int cols)
{
unsigned int i;
double** matrix;
matrix = (double** ) malloc(rows * sizeof(double *));
if (!matrix) { return NULL; }/* failed */
for (i = 0; i < rows; i++)
{
matrix[i] = (double *) malloc(cols*sizeof(double));
if (!matrix[i])
return NULL;
}
return matrix;
}
So, allocating memory to each i'th element within the array - is this the reason that we get ((matrix+i)+j) for the [i][j] - due to the fact that each element has its own memory block?

In C, there are no multidimensional arrays to the "true" sense (like in LISP, C# or C++/CLI). Rather than that, what you can declare is array of arrays (or array of pointers, where each pointer is assigned by malloc etc.). For instance:
int matrix[2][3];
defines two-elements array, where each element is of type array of three ints.
Now, when you refer to an ultimate array element, you need to first derefence into that inner array, then into the int object:
int value = matrix[2][3];
which is equivalent to:
int value = (*(*(matrix + 2) + 3));

a[i] is a syntactic sugar for *(a + i). That means that a[3][3] is equivalent to *(*(a + 3) + 3).
One other thing is notable, 3[a] is equivalent to *(3 + a) which is *(a + 3), which is a[3].

Related

Array without the use of [] index operator [duplicate]

I am trying to print a 2D matrix with using [], instead I want to use * like a pointer.
So with a 1 D array I'd do: *(arr+i) for example.
What's the syntax used to replace in matrix[][] ?
Here's the code:
for (i = 0; i < size; i++)
{
for (j = 0; j < (size * 2); j++)
{
printf(" %5d", matrix[i][j]);
}
printf("\n");
}
P.S,
I did try several things like:
*(matrix+i+j);
*(matrix+i)+*(matrix+j);
Of course none of that worked.
Thank you for your help and time!
Use the * two times. Each of * will basically replace one []:
*(*(matrix+i)+j)
You can try this-
*(*(matrix+i)+j) //reduce level of indirection by using *
This may depend on how matrix was allocated or passed to a function.
int A[10][15];
This uses a contiguous block of memory. To address the elements without using array notation use:
A +(i*15)+j // user694733 showed this is wrong
((int *)A)+(i*15)+j // this is horribly ugly but is correct
Note the 15, as each row consists of 15 elements. Better solutions are presented in other answers here.
In the following:
int *A[10];
A is an array of 10 pointers to ints. Assuming each array element has been allocated using malloc, you address the elements without using array notation as:
*(A+i) + j;
that is, you take A, then take the ith element, dereference that and add j as the second index.
--EDIT--
And to be complete:
int foo(int *p)
here a function just receives a pointer to zero or more ints. The pointer points to a contiguous, linear block of memory into which you can place an n-dimensional array. How many dimensions there are and the upper bound of each dimension the function can only know through parameters or global variables.
To address the cells of the n-dimensional array, the programmer must calculate the addresses him/herself, using the above notation.
int foo3(int *m, int dim2, int dim3, int i, int j, int k)
{
int *cell = m + i*dim3*dim2 + j*dim2 + k;
return *cell;
}

C: Pointer to 2-dimensional array of pointers

I am trying to solve the following issue but could not succeed yet:
I have a two-diwmensional array of pointers:
int* a[16][128];
Now I want to make a pointer to this array in that way that I can use pointer arithmetic on it.
Thus, something like this:
ptr = a;
if( ptr[6][4] == NULL )
ptr[6][4] = another_ptr_to_int;
I tried already some variations but it either fails then on the first line or on the if condition.
So, how can it be solved? I would like to avoid template classes etc. Code is for a time critical part of an embedded application, and memory is very limited. Thus, I would like ptr to be only sizeof(int*) bytes long.
A pointer to the first element of the array (which is what you want) could be declared as
int* (*ptr)[128];
A pointer to the array itself would be
int* (*ptr)[16][128];
and is not what you're looking for.
Thing you seem to want:
int* (*ptr)[128] = a;
Actual pointer to the array:
int* (*ptr)[16][128] = &a;
To start with array pointer basics for a 1D array, [tutorialspoint][1] has a very easy to ready description. From their example:
#include <stdio.h>
int main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance; //Here the pointer is assign to the start of the array
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) ); // Note the post increment
}
return 0;
}
There are a couple of relavent Stack overflow answers that describe 2D arrays:
How to use pointer expressions to access elements of a two-dimensional array in C?
Pointer-to-pointer dynamic two-dimensional array
how to assign two dimensional array to **pointer ?
Representing a two-dimensional array assignment as a pointer math?
[1]: https://www.tutorialspoint.com/cprogramming/c_pointer_to_an_array.htm

Single dynamic allocation for multi-dimensional array

The basic question is:
For code that expects a pointer to pointer that will be syntactically indexed like a 2-dimensional array, is there a valid way to create such an array using a single allocation?†
While on the surface, it seems I am asking for how to do so (like in this question), I already understand how it could be done (see below). The problem is that there might be an alignment issue.&ddagger;
The rest of the text describes some alternatives, and then explains the method under question.
† Olaf points out a pointer to pointer is not a 2-dimensional array. The premise of the question is that 3rd party code expects a pointer to pointer passed in, and the 3rd party code will index it as a 2-dimensional array.
&ddagger; ErikNyquist presented a possible duplicate which explains how one might perform such an allocation, but I am questioning the validity of the technique with regards to alignment of the data.
If I need to dynamically allocate a multi-dimensional array, I typically use a single allocation call to avoid an iteration when I want to free the array later.
If VLA is available, I might code it like this:
int n, m;
n = initialize_n();
m = initialize_m();
double (*array)[m] = malloc(n * sizeof(*array));
array[i][j] = x;
Without VLA, I either rely on a macro on a structure for array accesses, or I add space for the pointer table for code that expects the ** style of two-dimensional array. The macro approach would look like:
struct array_2d {
int n, m;
double data[];
};
// a2d is a struct array_2d *
#define GET_2D(a2d, i, j) (a2d)->data[(i) * x->n + (j)]
struct array_2d *array = malloc(sizeof(*array) + n * m * sizeof(double));
array->n = n;
array->m = m;
GET_2D(array, i, j) = x;
The pointer table method is more complicated, because it requires a loop to initialize the table.
struct array_p2d {
int n, m;
double *data[];
};
#define GET_P2D(a2d, i, j) (a2d)->data[i][j]
struct array_p2d *array = malloc(sizeof(*array) + n * sizeof(double *)
+ n * m * sizeof(double));
for (k = 0; k < n; ++k) {
array->data[k] = (double *)&array->data[n] + k * m;
}
GET_P2D(array, i, j) = x;
// array->data can also be passed to a function wanting a double **
The problem with the pointer table method is that there might be an alignment issue. As long as whatever type the array is of does not have stricter alignment requirements than a pointer, the code should work.
Is the above expected to always work? If not, is there a valid way to achieve a single allocation for a pointer to pointer style 2-dimensional array?
Well, your malloc allocation is guaranteed to be aligned (unless you're using a non-standard alignment), so all you need to do is to round up the pointer table size to the alignment of the data segment:
const size_t pointer_table_size = n * sizeof(double *);
const size_t data_segment_offset = pointer_table_size +
((_Alignof(double) - (pointer_table_size / _Alignof(double))) % _Alignof(double));
double **array = malloc(data_segment_offset + (n * m * sizeof(double));
double *data = (double **)(((char **) array) + data_segment_offset);
for (int i = 0; i != n; ++i)
array[i] = data + (m * i);

Write a signature of function accepts all 2D arrays of type int as parameter regardless of the method the user chose?

An example to illustrate:
#include <stdlib.h>
#include<stdio.h>
void simple_function(int s , int array[][s]);
int main(void){
int x;
/*Static 2D Array*/
int array[2][2];
/*Many Methods to Dynamically Allocate 2D Array....for example*/
/* Using Array of pointers*/
int *array1[2];
for(x=0;x<2;x++){array1[x] = calloc (2, sizeof(int));}
/*Using pointer to a pointer */
int **array2 = calloc (2, sizeof(int*));
for(x=0;x<2;x++){array2[x] = calloc (2, sizeof(int));}
/*Using a single pointer*/
int *array3 = calloc (4 , sizeof(int));
/* Codes To Fill The Arrays*/
/*Passing the Arrays to the function, some of them won't work*/
simple_function(2, array); /*Case 1*/
simple_function(2, array1); /*Case 2*/
simple_function(2, array2); /*Case 3*/
simple_function(2, array3); /*Case 4*/
return 0;
}
void simple_function (int s, int array[][s]){
int x,y;
for(x=0;x<s;x++){
for(y=0;y<s; y++){
printf ("Content is %d\n", array[x][y]);
}
}
}
My Question:
Is there a way to write the signature of the simple_function to let it accepts all cases regardless of the method that the user chose? If not, what is the most preferable for the function if I want to make a library?
You've actually declared two different types of objects, as shown below
Your array and array3 are both stored in memory as 4 contiguous ints. There's no additional information, you've simply reserved space for 4 ints, and the C specification requires that they are contiguous.
However, array1 and array2 are actually pointer arrays. Your code reserves memory for an array of two pointers, and each pointer points to an array of two ints. The ints will be arranged in groups of two, but the groups can be scattered anywhere in memory.
From this, it should be clear that the compiler cannot use the same code to access both types of array. For example, let's say that you're trying to access the item at array[x][y]. With a contiguous array, the compiler computes the address of that item like this
address = array + (x * s + y) * sizeof(int)
With a scattered array, the compiler computes the address like this
pointer = the value at {array + x * sizeof(int *)}
address = pointer + y * sizeof(int)
So you need two functions to handle those two cases. For the contiguous array, the function looks like this
void showContiguousArray( int s, int array[][s] )
{
for ( int x=0; x<s; x++ )
for ( int y=0; y<s; y++ )
printf( "array[%d][%d] = %d\n", x, y, array[x][y] );
}
For the scattered array, the function is
void showScatteredArray( int s, int **array )
{
for ( int x=0; x<s; x++ )
for ( int y=0; y<s; y++ )
printf( "array[%d][%d] = %d\n", x, y, array[x][y] );
}
Notice that those functions are identical, except for one thing, the type of the array argument. The compiler needs to know the type in order to generate the correct code.
If the array is declared in the same scope where it's used, then all of these details are hidden, and it seems that you're using the exact same code to access different types of arrays. But that only works because the compiler knows the type of the array from the earlier declaration. But if you want to pass the array to a function, then the type information must be explicitly specified in the function declaration.
Is there a way to write the signature of the simple_function to let it accepts all cases regardless of the method that the user chose?
"All the cases" apparently describes the different declarations array, array1, array2, and array3, the latter three of which are described in code comments as "Methods to Dynamically Allocate 2D Array." But none of the four types are the same as any of the others, and none of the latter three in fact declare 2D arrays nor pointers to such. None of them are even compatible with each other. Of the dynamic ones, only array3 can even usefully be converted to something comparable to array.
A dynamically-allocated 2D array would be referenced via a pointer of this type:
int (*array4)[2];
array4 = calloc(2 * sizeof(*array4));
So, no.
If not, what is the most preferable for the function if I want to make a library?
It depends on your objectives. If your function must be compatible with static 2D arrays, then something of the general form you presented, plus or minus the variable dimension, is the only alternative. If you want to support the pointer-to-pointer form, then that's fine, and usable with declarations like array1's and array2's, but not with array, array3, or array4.
Assuming that you want this for 2D arrays, perhaps this can get you started ...
void simple_function(int s, int t , int* array) {
int i, j;
for (i=0; i<s; i++) {
for (j=0; j<t; j++) {
// accessing your array elements
printf(" %d", *(array + i*t + j));
}
printf("\n");
}
}
int main(void)
{
int array[2][3];
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1][0] = 11;
array[1][1] = 12;
array[1][2] = 13;
array[2][0] = 21;
array[2][1] = 22;
array[2][2] = 23;
simple_function(3, 3 , array);
return 0;
}
The expression int **array2 is not a 2D array by the way, it is a variable that holds the address of a pointer variable.

how to pass 1D and 2D array arguments to a function in c

Suppose I have a function, int function(int N, int c[N]){...}, taking as parameters an integer and an array. Suppose now I have a double array **c of size 'N times 2' and suppose, I want to apply the function function to one column of the double arrow, c[i][0], i varying from to N-1. How am I supposed to use this function. Does it looks like something like function(N,*c[0]) ?
Does anyone can help ?
An array in C always decays to a pointer to its first element when passed into a function. This is good to know in some situations.
As an example, you could write
int list[10];
func (int *x) {
int i;
for (i = 0; i < 10; i++) {
printf("%d", x[i]);
}
}
x[i] is really just syntactic sugar. In C, when you use bracket notation to access an element of an array, it gets converted to *(x + i), where x is the name of the array.
This works because of pointer arithmetic. If x is the name for an array of 10 integers, then the value of x in an expression is the address of the first integer of the array.
x + i will always point to the i-th element after x (C takes into account the size of the element type stored in the array, and increments the pointer accordingly).
Thus, when passing 2d arrays, the array decays to a pointer to its first element - which is an array.
A function signature taking a 2d array can be written as
func(int x[][columns] {
...
}
// but could also be written as
func(int (*x)[columns]) {
...
}
which indicates that x is a pointer to an array of integers.
Sometimes you need to write a function to accept a 2 dimensional array where the width is not known until run time. In this case, you can pass a pointer to the [0][0] element and also pass the two dimensions, and then use pointer arithmetic to get the right element. For example,
print_2d_array (int *x, height, width) {
int i, j;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
printf("%d", x[i * width + j]);
}
}
}
int list[10][10];
print_2d_array (&list[0][0], 10, 10);
would work for a dynamically allocated 2d array.
In c langauge, for single dimentional array you no need to mention the size of the array in the function arguments while passing an array to that function.
If it is a single dimentional array
...
int a[10];
func(10, a);
...
void func(int size, int x[]) //no need to mention like int x[10]
{
//here x is not an array. Its equivalent to int *
printf("%d", sizeof(x)); // this will print 4 or 8 not 40
}
If it is 2D array
...
int a[10][5];
func (10, a);
...
void (int rows, int x[][5]) //here int x[][] is invalid
{
}

Resources