C - Convert array of elements into 2-d matrix

2 dimensional array in c
convert 1d array to 2d array c++
two dimensional string array in c
sum of elements in 2d array in c
two dimensional array in c++
two-dimensional array example
two dimensional array in c definition
one dimensional array in c

It might be a stupid question, but I wonder if there is a efficient way to do this.

The situation:

int* array = malloc(n * m * sizeof(int));
//want to convert array into M[n][m]

what I am doing now:

int** M = malloc(n * sizeof(int*));
for(int i = 0; i < n; i++, array += m)
  M[i] = array; 

I don't think the conversion should be this complex. Is there any simple syntax C provided? Can I declare an extern M[n][m] then set its address to the array?

(error handling and memory management in the sample is omitted for simplicity. Just think it as a part of some function.)

After:

int* array = malloc(n * m * sizeof(int));

you can do:

int (*M)[m] = (int(*)[m])array;

and then use M[1][2] for example.

You could have done that in the first place too :

int (*M)[m] = malloc( n * sizeof *M );

Two dimensional (2D) arrays in C programming with example, The two dimensional (2D) array in C programming is also known as matrix. This program demonstrates how to store the elements entered by user in a 2d  How to convert a 2-d array of size (m x n) into 1-d array and how to store the element at position [i, j] of 2-d array in 1-d array? Clearly, the size of 1-d array is the number of elements in 2-d array i.e. (m x n). If the elements in the 2-d array are stored in row-major order.

The tricky part is declaring the variable to hold the pointer to the allocated array; the rest is straight-forward — assuming you have a C99 or later compiler.

#include <stdio.h>
#include <stdlib.h>

static void print_2dvla(int rows, int cols, int data[rows][cols])
{
    for (int i = 0; i < rows; i++)
    {
        printf("%2d: ", i);
        for (int j = 0; j < cols; j++)
            printf(" %4d", data[i][j]);
        putchar('\n');
    }
}

int main(void)
{
    int m = 10;
    int n = 12;

    int (*M)[m] = malloc(n * m * sizeof(M[0][0]));
    if (M == NULL)
    {
        fprintf(stderr, "Failed to allocate %zu bytes memory\n", n * m * sizeof(M[0][0]));
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
            M[i][j] = (i + 1) * 100 + (j + 1);
    }

    print_2dvla(n, m, M);

    free(M);
    return 0;
}

Example output:

 0:   101  102  103  104  105  106  107  108  109  110
 1:   201  202  203  204  205  206  207  208  209  210
 2:   301  302  303  304  305  306  307  308  309  310
 3:   401  402  403  404  405  406  407  408  409  410
 4:   501  502  503  504  505  506  507  508  509  510
 5:   601  602  603  604  605  606  607  608  609  610
 6:   701  702  703  704  705  706  707  708  709  710
 7:   801  802  803  804  805  806  807  808  809  810
 8:   901  902  903  904  905  906  907  908  909  910
 9:  1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
10:  1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
11:  1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

The key line is:

int (*M)[m] = malloc(n * m * sizeof(M[0][0]));

This says that M is a pointer to an array of int arrays each of which has the dimension m. The rest of the code simply uses that array with the usual 2-subscript notation — M[i][j] etc. It can be passed to functions. I've not shown it here, but it is trivial to put the initialization code into a function too, and then have several different sizes of matrix in a single function.

How to take a 1d array and convert the array to a 2d array in a c++ , How do I take a 1d array and convert the array to a 2d array in a c++ function so the You can make an array of arrays (NOT the same as a 2D array) and access elements using the What do you mean by converting an array into a matrix? Get the matrix with most of its elements as 0. Create a new 2D array to store the Sparse Matrix of only 3 columns (Row, Column, Value).; Iterate through the Matrix, and check if an element is non zero.

C - Convert array of elements into 2-d matrix, C - Convert array of elements into 2-d matrix. C - Convert array of elements into 2​-d matrix. It might be a stupid question, but I wonder if there is a efficient way to  Convert the given 2D array into a 1D array. Sort the 1D array; Convert 1D to Spiral matrix; This can be solved by 4 for loops which store all the elements. Every for loop defines a single direction movement along with the matrix.

Use an array of pointers.

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int n = 3, m = 4, i, j, count=0;

    int *array[n];
    for(i=0; i<n; i++)
     array[i] = (int *)malloc(m * sizeof(int));
     if( array[i] == NULL)
     {
        perror("Unable to allocate array");
        exit(1);
     }

    // going to add number to your 2d array.

    for (i = 0; i < n; i++)
      for (j = 0; j < m; j++)
         array[i][j] = ++count;

    for (i=0; i < n; i++)
      for (j=0; j < m; j++)
         printf("%d ", array[i][j]);

      // free memory

      for(i=0; i<n; i++)
         free(array[i]);

     }

Converting one dimensional array to two dimensional array, For example, one matrix can be a submatrix of another; or a one-row or one-​column matrix (a vector) can be the diagonal elements of a square  Write a C program to count total number of even and odd elements in an array. Write a C program to count total number of negative elements in an array. Write a C program to copy all elements from an array to another array. Write a C program to insert an element in an array. Write a C program to delete an element from an array at specified

How to dynamically allocate a 2D array in C?, A simple way is to allocate memory block of size r*c and access elements using simple pointer arithmetic. filter_none. edit close. play_arrow. link brightness_4 Convert a String to Integer Array in C/C++; Convert a Singly Linked List to an array; Convert one array to another using adjacent swaps of elements; Minimum increments to convert to an array of consecutive integers; Convert to Strictly increasing integer array with minimum changes; Convert an array to reduced form | Set 2 (Using vector of pairs)

Emulating a 2-d array using 1-d array, that no employee feels unfair · How to flatten a Vector of Vectors or 2D Vector in C++ How to convert a 2-d array of size (m x n) into 1-d array and how to store the element at position [i, j] of 2-d array in 1-d array? If the elements in the 2-d array are stored in row-major order. C++ program to emulate 2-d array using. Conversion of a 2D array into 1D array can be of two types : 1. Row wise 2. Column wise Example : 2D array : {1, 2, 3 4, 5, 6 7, 8, 9} 1D array Row wise : {1, 2, 3, 4

C Multidimensional Arrays (2d and 3d Array), In this tutorial, you will learn to work with multidimensional arrays (two-​dimensional and three-dimensional arrays) in C programming with the help of examples. Convert array to arraylist and vice-verse a[2][2], b[2][2], result[2][2]; // Taking input using nested for loop printf("Enter elements of 1st matrix\n"); for (int i = 0; i < 2;  Minimum cost to convert 3 X 3 matrix into magic square; Python | Convert a list of characters into a string; Convert given string so that it holds only distinct characters; Convert characters of a string to opposite case; Check if a given string can be formed using characters of adjacent cells of a Matrix; Maximum perimeter of a square in a 2D grid

Comments
  • C'mon man this is C, cast the pointer to what you want
  • @smac89 I want to use the syntax of index M[a][b] for some other reason.
  • Seems to work here: coliru.stacked-crooked.com/a/6790414229295052
  • @MadPhysicist, I was just about to comment the same as above. How is it computed in this case: coliru.stacked-crooked.com/a/39e6761edaccd062? Here the size is not known until runtime
  • @smac89 in the same way that you'd compute i + sp * j for any other variables. When you say int (*p)[sp], that means for a given i, j, multiply the j by sp before adding to i and using as an offset. All the compiler is doing is converting the manually computed linear offset into a fancy syntax that's easier to read.
  • I think the extern keyword prevent the variable allocating memory on stack. Also, it would not be in the static zone if I have it inside a function block.
  • It's feasible to argue that the int *array = malloc(…); cannot be a global variable because in C you cannot use the result of a function call to initialize a global (or static) variable.
  • Consider showing the code needed to free the allocated memory.
  • The thing is that I got an array initially (not an array of pointer), that is nothing I would like to mess with.
  • OK I freed the memory.
  • You can just use a 2d array and and the elements then, just array[m][n] and use a for loop to put the elements into the array. No malloc needed
  • While a good generic approach, usually, in my limited experience, two layers of indirection tends to be a tad slower than computing the linear index. And you shouldn't have any problems with syntax in light of this comment: stackoverflow.com/questions/54282732/…