Is it possible to define multidimensional arrays from user input in C where the user could specify the number of dimensions, eg:
1 => arr[x]
2 => arr[x][x]
3 => arr[x][x][x]
(c noob)
I dont see how this could be written without hardcoding, since working with the array would require passing it as a pointer to a pointer for every dimension.
Chameleonballs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5
The answer to your question is “yes.” It usually is when asking “is X possible?”
Here’s a first go at implementing it using a single dimensional dynamically allocated array, and then a bunch of math to get positions within it as though it actually is mult-dimensional. Dimensions and indices are hard-coded, but those arrays could be dynamically generated at runtime.
#include <stdlib.h>
#include <stdio.h>
struct multi_dim_array {
size_t ndimensions;
size_t *dimensions;
int *data;
};
struct multi_dim_array *make_multi_dim_array(size_t n, size_t *dims) {
if (n <= 0) return NULL;
struct multi_dim_array *arr = malloc(sizeof(*arr));
if (!arr) {
return NULL;
}
arr->ndimensions = n;
arr->dimensions = malloc(sizeof(size_t *) * n);
if (!arr->dimensions) {
free(arr);
return NULL;
}
size_t total_size = 1;
for (size_t i = 0; i < n; i++) {
if (dims[i] <= 0) {
free(arr->dimensions);
free(arr);
return NULL;
}
total_size *= dims[i];
arr->dimensions[i] = dims[i];
}
arr->data = malloc(sizeof(int) * total_size);
if (!arr->data) {
free(arr->dimensions);
free(arr);
return NULL;
}
return arr;
}
void set_multi_dim_array(struct multi_dim_array *arr, size_t *indices, int value) {
size_t offset = 0;
for (size_t i = 0; i < arr->ndimensions; i++) {
size_t sz = 1;
for (size_t j = i + 1; j < arr->ndimensions; j++) {
sz *= arr->dimensions[j];
}
offset += indices[i] * sz;
}
arr->data[offset] = value;
}
int get_multi_dim_array(struct multi_dim_array *arr, size_t *indices) {
size_t offset = 0;
for (size_t i = 0; i < arr->ndimensions; i++) {
size_t sz = 1;
for (size_t j = i + 1; j < arr->ndimensions; j++) {
sz *= arr->dimensions[j];
}
offset += indices[i] * sz;
}
return arr->data[offset];
}
int main(void) {
size_t dims[] = {2, 4, 3};
size_t idxs[] = {1, 2, 1};
struct multi_dim_array *arr = make_multi_dim_array(3, dims);
set_multi_dim_array(arr, idxs, 42);
printf("%dn", get_multi_dim_array(arr, idxs));
}
But that’s a lot of work, and you’d really want to read up on the XY problem to see if maybe you have one of those.