-1

I want to create a linked list that contains variable-length array-like int A[n][n].

I tried to do it like this, but I'm getting the error Incomplete type is not allowed.

struct Node {
 int A[n][n];
 struct Node* next;
};

Is there any way to do this in c?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
anfjnlnl
  • 63
  • 7

1 Answers1

0

You'll need to use an int ** allocated on the heap in order to have a variable length. To do that, you need a constructor and a destructor. I also added the ability to specify the next node in the constructor.

struct Node{
    size_t size;
    int **A;
    struct Node* next;
};

void construct_node(struct Node *node, size_t n, struct Node *next_node) {
    node->size = n;
    node->A = malloc(n * sizeof(int *));
    for (size_t i = 0; i < n; i++) {
        node->A[i] = malloc(n * sizeof(int));
    }
    node->next = next_node;
}

void destruct_node(struct Node *node) {
    for (size_t i = 0; i < node->size; i++) {
        free(node->A[i]);
    }
    free(node->A);
    // You probably also want to call destruct_node on the next node to free the entire list:
    // if (node->next) destruct_node(node->next);
}

After doing this, the following code will be required for creating your node:

int size = 10;
struct Node your_node;
construct_node(&your_node, size, NULL);

// Do your stuff with the node

destruct_node(&your_node);
altermetax
  • 696
  • 7
  • 16