I am new to C, just try to understand a very tiny part of a problem I have a simple program -1 represents the end of the array :
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct List list_t;
struct List {
void * head;
list_t * tail;
};
list_t * makelist(void * x, list_t * xs){
list_t * ans = (list_t *) malloc(sizeof(list_t));
ans->head =x;
ans->tail = xs;
return ans;
}
list_t * makeListFromIntArray(int list[]){
list_t * ans = (list_t *) malloc(sizeof(list_t));
int i = 0;
while(list[i]!=-1){
ans = makelist((void *)(intptr_t)list[i],ans);
i++;
}
return ans;
}
void printList(list_t * xs){
while(xs != NULL){
printf("%lu\n",((intptr_t)xs->head));
xs = xs->tail;
}
}
int main() {
int s[] = {1,2,3,4,5,-1};
list_t * xs = makeListFromIntArray(s);
printList(xs);
return 0;
}
The main problem is when printList executes I am getting a zero at the end.
5
4
3
2
1
0
Process returned 0 (0x0) execution time : 0.001 s
Press ENTER to continue.
This is my main problem and the minor problem is the array is reversed which is understandable. I can overcome this by reversing before feeding into makelistfromintarray. However I am open more elegant solutions.