I'm currently starting out with C so I thought I'd try creating my own custom list. Here's the code:
#include <stdio.h>
struct list {
char data[10];
struct list *n;
};
void clist(struct list *a) {
int j=(sizeof(a)/sizeof(a[0]));
j--;
for(int i=0; i<j-1; i++) {
struct list *next=&a[i+1];
a[i].n=next;
}
}
int main() {
struct list first = {.data="one", .n=NULL};
struct list second = {.data="two", .n=NULL};
struct list third = {.data="three", .n=NULL};
struct list arr[] = {first, second, third};
struct list *p=&arr[0];
clist(p);
struct list looper = first;
while(looper.n!=NULL) {
printf("%s ", looper.data);
looper = *looper.n;
}
return 0;
}
So basically I have a struct that saves a char array and a pointer. I initialize them and then I try to link them together by giving it to the clist method. There lies the problem: it seems clist isn't getting anything useful as the variable j stays at 0. If I do the whole size calculation before giving the array to the clist method, I'm getting the correct 3 as a result. Why is that?