0

So I'm trying to make an array of linked lists, at first I had the following code:

typedef struct node{
    int data;
    struct node *next;
} node;

struct ko {
    struct node *first;
    struct node *last;
} ;

struct ko array[6];

with this code the rest of the program runs fine, however, i would like the user to be able to define the array size when the program starts, after some research I believe it should be something like this:

the .h file

typedef struct node{
    int data;
    struct node *next;
} node;



struct ko {
    struct node *first;
    struct node *last;
} ;

struct ko *array;

the main.c file:

int size;
printf("array size: ");
scanf("%d", &size);
array = malloc(sizeof(struct ko) * size);

With this code the program compiles fine, but it just gets stuck when it runs, it doesn't crash, it just doesn't do anything... So I'm wondering if the problem is in this code, or elsewhere in the program.. thank you

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 1
    Is the program stuck at scanf("%d", &size); ? – akhil May 23 '13 at 09:31
  • 2
    Can you provide more context? What code do you have after `malloc`? What do you mean by stuck? – srikanta May 23 '13 at 09:31
  • not your question, BUT: IF you "typedef struct node {...} node;" then you should use "node *first;". If you name your child "kleiner" it is very confusing for everybody else when you call him "hey du". To your question: elsewhere – Peter Miehle May 23 '13 at 09:31
  • 1
    What gets stuck ? The code you showed actually does nothing but allocating memory after a user input (or is it there that it gets stuck ?). And by the way, be careful, you're allocating memory for 2 pointers to `struct node`, not for two `struct node`, which is different. – JBL May 23 '13 at 09:31
  • Also, you seemed to have asked this question earlier. Why duplicate? http://stackoverflow.com/questions/16688372/how-to-make-a-user-defined-array-of-struct-in-c – srikanta May 23 '13 at 09:36
  • it is not expected to do any thing.In main it is just asking size of array and allocating memory required for that size.Now it won't do anything because you have not written anything. – Dayal rai May 23 '13 at 09:45
  • it gets stuck when its supposed to start adding data to the linked lists, however, that function does works fine when I do a static allocation of the array as in the first code. – user2408804 May 23 '13 at 11:41

2 Answers2

0

Well there's nothing here that's immediately wrong... Just make sure to zero-initialize the array contents (the actually 100% portable way is with a for loop, but using calloc() works on all usual platforms).

Medinoc
  • 6,577
  • 20
  • 42
0

There is only one mistake in the program, malloc returns void*, you need to type case it to (struct ko*). Apart from this I don't see any error. I did check the same program in VS also. it is working fine.