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 []?

3
  • 1
    What is the question ? Commented Nov 6, 2017 at 5:51
  • Should be possible with appropriate (local) VLA typedef (and type cast or helper variable of that type). Commented Nov 6, 2017 at 6:28
  • If C++ is an option, check out xtensor Commented Nov 6, 2017 at 6:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

well this works only directly for arrays where the element types are big enough to hold the dimensions...
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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.