0

In numpy, you can access the size and shape of the array with array.size and array.shape while elements can be accessed using array[i].

How does one achieve this with a C structure? One can do something like

struct{
    int size;
    int shape[2];
    int *elements;
} int_array;

but then elements can be accessed as

int_array.elements[i].

not like numpy.

How can I have an array that stores size and shape, but whose elements can be accessed in the usual way using []?

Eric
  • 95,302
  • 53
  • 242
  • 374
Navdeep Rana
  • 111
  • 1
  • 7

2 Answers2

2
  1. Allocate an array that is 3 cells bigger than you need.
  2. Put size and shape in the first 3 cells
  3. Increment the pointer by 3 * sizeof(int).
  4. Write accessors for size and shape.

You can then access the array in the usual way.

Don't forget to subtract 3 * sizeof(int) from the pointer before you free it.

1

You could use a simple macro to cast your pointer to a 2D array (source):

#define INDEX(a) ((int(*)[a.shape[1]]) a.elements)

Which you can use as

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

typedef struct{
    int size;
    int shape[2];
    int *elements;
} int_array;


int main() {
    int_array arr;
    arr.shape[0] = 2;
    arr.shape[1] = 3;
    arr.elements = malloc(6*sizeof(*arr.elements));

    INDEX(arr)[0][1] = 2;

    printf("%d", INDEX(arr)[0][1]);
}
Eric
  • 95,302
  • 53
  • 242
  • 374