Reputation: 43
I want to have a 2D array where the first element is just an int
and the second element is an empty array, something like this: [[0, []], [0, []], ...,[0, []]]. This can be easily done through Python:
array = [[0, []] for i in range(n)]
I'll be putting int
data in every empty array inside the array.
Here's my attempt:
struct node
{
int value;
Node* next;
};
struct foo
{
int n;
node innerArray;
};
Upvotes: 0
Views: 48
Reputation: 222526
In C, an array is a sequence of objects with a fixed member type and the array cannot be empty. C 2018 6.2.5 20 says:
An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type.
So it is not possible to have an array in which the elements have different types.
To combine different types into a single object, you can use a structure. For example, a structure with an int
member followed by an array of ten double
could be:
struct foo
{
int n;
double d[10];
};
Then you can make an array of these structures with struct foo x[23];
.
I'll be putting int data in every empty array inside the array.
To manage arrays of varying size, you must allocate and free memory by calling appropriate routines, such as the standard library routines malloc
, realloc
, and free
. In this case, instead of defining the structure to have a fixed-length array, you can use a pointer:
struct foo
{
int n;
int *p;
};
To create an array of these, you might use code like:
#define NumberOfX 23
struct foo x[NumberOfX];
for (int i = 0; i < NumberOfX; ++i)
{
x[i].n = 0;
x[i].p = NULL;
}
This initializes all of the pointers to a null pointer, which might serve as an empty array for you.
When you want to allocate memory for an array, you could use:
x[i].p = malloc(NumberOfElements * sizeof *x[i].p);
After this, you check whether the allocation succeeded:
if (!x[i].p)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
When you want to change the size of the array, use realloc
:
int *NewPointer = realloc(x[i].p, NewNumberOfElements * sizeof *x[i].p);
if (!NewPointer)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
x[i].p = NewPointer;
When you are done with an array, release the memory with free(x[i].p);
.
Upvotes: 1