Use the correct types
Use size_t
instead of int32_t
for the array size and index. Using int32_t
will limit it to arrays containing 2,147,483,647 elements even if you compiled it for 64-bit mode.
Also, note that it does not make sense to check if i
or length
is less than zero since it is unsigned.
Node* array_to_list(int32_tint array[], size_t length) {
// ...
for (size_t i = 0; i < length; i++) {
Node* current = malloc(sizeof(Node));
current->data = array[length - 1 - i];
current->next = tail;
tail =// current;...
}
return tail;
}
Check if malloc was successful
You cannot simply assume that there will be enough memory available. I would suggest something like the following:
Node* current = malloc(sizeof(Node));
if (current == NULL)
{
fprintf(stderr, "Out of memory error");
exit(EXIT_FAILURE);
}
Putting it all together:
Putting it all together:
Node* array_to_list(int32_tint array[], size_t length) {
Node* tail = NULL;
for (size_t i = 0; i < length; i++) {
Node* current = malloc(sizeof(Node));
if (!current == NULL)
{
fprintf(stderr, "Out of memory error");
exit(EXIT_FAILURE);
}
current->data = array[length - 1 - i];
current->next = tail;
tail = current;
}
return tail;
}
int main() {
int array[] = { 1, 2, 3, 4, 5 };
struct Node* list = array_to_list(array, sizeof(array) / sizeof(array[0]));
for (Node* node = list; node; node = node->next)
printf("%d\n", node->data);
free_list(list);
}