"...How can I achieve this?"
Probably not using arrays.
Arrays in C
are rigidly defined contiguous sets of memory locations, created on the stack. This type of array is generally recommended over dynamically allocated variations when size, shape of the array are known at compile-time. Once created, the size and shape of the array created with this method is not changeable. Arrays can be created for a single type
variables, as well as for struct
type data, allowing variations of type to exist within each array element.
When run-time flexibility is needed there are other methods to consider, such as the following:
- Dynamically allocated arrays. Although commonly referred to as arrays, are actually blocks of addressable (and depending on how implemented, may be contiguous) memory created on the heap. These are created in any number of dimensions, and like arrays, elements are accessible via indexing, eg
array[i][j][k]
. This type of dynamic array is recommended over a normal C array
only when the size or shape of the array is not known until run-time. Once created its dimensions can be changed, but not easily. i.e. Requiring freeing of pointers, and reallocation of new memory in the shape of new dimensions.
- Linked List. This method is similar to the previous method in that it uses dynamically allocated memory during its creation, but vastly different in terms of its flexibility. Linked Lists use a
struct
based architecture, with each instance of struct (or node) containing members of data related in some way, analogous to the fields contained within a database record. Linked List nodes can be inserted, deleted, searched and sorted.
Given the explicit stated requirement: "I'd like to make a 1D array 2D"
And the implied shape of your data:
patches[0][0] = "Version 1.01";
patches[0][1] = "Size 1GB";
patches[0][2] = "Is compatible";
patches[1][0] = "Version 4.01";
patches[1][1] = "Size 4GB";
patches[1][2] = "Is compatible";
Linked List stands out as the best suited option. Following is an example that could be used as the struct
(or node
) design for a flexibly sized and searchable list that would support what you are doing:
typedef struct patch {
int item;
char ver[80];
long sz;
char cmpat[80];
struct patch *next;
}NODE;
Following is a brief example of inserting a node:
In main()
...
NODE *head = malloc(sizeof(*head));
if(head)
{
insertNode(NODE **head, 1001, "Version 1.01", 1e9, "Is compatible");
insertNode(NODE **head, 1002, "Version 4.01", 4e9, "Is compatible");
}
...
Where insertNode
is defined as:
void insertNode(NODE **head, int item, char *ver, long sz, char *cmpat)
{
//allocate new node
NODE *new_node = malloc(sizeof(NODE));;
new_node->item = val;
strcpy (new_node->data, ver);
new_node->sz = 4e9;
strcpy(new_node->cmpat, cmpat);
(*head) = new_node;
}