0

I create a dynamic integer matrix(2X2) in c with malloc

int *ptr=malloc(sizeof(int)*4);

I succeed to access the matrix with one index [(i*2)+j] and not with two indexes like [i][j]. Are dynamic matrix can access only with one index, or am I wrong somewhere? thanks

  • Your allocation is incorrect. It allocates a 1 dimensional array and not a 2 dimensional array. Please do a search. There are many questions on exactly the same thing. For example: [Memory allocation for 2D array in C](http://stackoverflow.com/questions/8778285/memory-allocation-for-2d-array-in-c) – kaylum Dec 26 '15 at 10:25
  • You have to decide whether you want contiguous memory or a jagged array. – David Heffernan Dec 26 '15 at 10:50

2 Answers2

0

You need to declare your matrix as a pointer to an integer pointer. Here is an example:

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

#define NEW_ARRAY(ptr, n) \
    { \
        (ptr) = malloc((n) * sizeof (ptr)[0]); \
        if ((ptr) == NULL) { \
            fprintf(stderr, "error: Memory exhausted\n"); \
            exit(EXIT_FAILURE); \
        } \
    }

int main(void)
{
    const int m = 2, n = 2;
    int **A;
    int i, j;

    /*allocate matrix*/
    NEW_ARRAY(A, m);
    for (i = 0; i < m; i++) {
        NEW_ARRAY(A[i], n);
    }

    /*initialize matrix*/
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            A[i][j] = i + j;
        }
    }

    /*print matrix*/
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%d ", A[i][j]);
        }
        putchar('\n');
    }

    return 0;
}
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60
0

Are dynamic matrix can access only with one index, or am I wrong somewhere?

You can with two indexes like [i][j] by defining it appropriately:

    int (*ptr)[2] = malloc(sizeof(int)*4);
Armali
  • 18,255
  • 14
  • 57
  • 171