Can someone tell me if i'm writing this C code right?
I wrote the code inside the function "createList" everything else was given.
@wio @ganeshie8 @Luigi0210
@.Sam.
@freckles
presumably you mean something like struct List *createList(int maxElements) { struct List *list = malloc(sizeof(struct List)); list->sortedList = malloc(sizeof(int) * maxElements); list->size = 0; list->maxSize = maxElements; return list; }
no the function signature and all were given. we're only filling in the funcitons.
so it has to be list* createList(int maxElement)
surely you mean List not list? and that is using C++ not C syntax for struct types
hmm, it says list*
that's the code the professor gave.
well regardless, the body should be correct
aside from some explicit casting
and why is it not c? the professor told us it was c.
and what do you mean by explicit casting?
C would require a typedef for you to use list or List to refer to struct List
Sorry there was a typedef, i just didn't ahve it in screen shot struct List *list = malloc(sizeof(struct List)); list->sortedList = malloc(sizeof(int) * maxElements);
can you explain those above two lines?
and why does what i did, not work?
the first allocates a List object on the heap by requesting some block of memory big enough to fit a List (int *, int, int); the second line then allocates the internal 'array' used by the list for storing elements (enough space for maxElement number of int)
wait how do you know it allocates an internal array?
for one, sizeof(maxElements) is returning the sizeof the int variable which is probably 4 on your system; presumably you meant to allocate an array capable of holding maxElement number of int, in which case you meant sizeof(int) * maxElements. but then this shouldn't be the List object itself but its internal sortedList member which is presumably an internal array
eh, it's the only tihng that seemed sensible; otherwise, where does it store list entries?
so by doing sizeof(int)*maxelements, it creates 4bytes times the maxElements amount of space?
and dont' you need list *sortedList = (list *)malloc(sizeof(maxElements)); ^^^^^ that in the first line?
well, it requests a block of memory big enough to contain at least maxElements number of int (so if sizeof(int) = 4 then it allocates 4*maxElements number of bytes, yes)
we used that in a previous class. but i wasn't quite sure why we did that.
where we did (list *) and then malloc.
i don't rmemeber if the C compiler just warns you about the implicit pointer conversion but in case it actually spits out an error, yes, you would need an explicit cast there
ooo!
Join our real-time social learning platform and learn together with your friends!