-1

When creating a linked list in the following way, I understand everything that is happening except for:

curr = (item *)malloc(sizeof(item));

I get that you are allocating enough memory for the size of an item struct, but what exactly are you doing with (item *) ? Is this meant to be pointer notation or multiplication?

#include<stdlib.h>
#include<stdio.h>

struct list_el {
   int val;
   struct list_el * next;
};

typedef struct list_el item;

void main() {
   item * curr, * head;
   int i;

   head = NULL;

   for(i=1;i<=10;i++) {
      curr = (item *)malloc(sizeof(item));
      curr->val = i;
      curr->next  = head;
      head = curr;
   }

   curr = head;

   while(curr) {
      printf("%d\n", curr->val);
      curr = curr->next ;
   }
}
Michael
  • 3
  • 1
  • 1
    This is pointer notation. Assuming you don't know extreme C, using (item *) you are setting your pointer type to `item *` type after `alloc`ating block of memory of `item` size. And this is not multiplication, this is pointer. Read about `malloc` if it helps you (again, I am assuming you are new to C and have probably done other langs like C++/Java) – ha9u63a7 Oct 27 '14 at 10:34
  • 1
    You should read about pointers and C. Your question here basically defies the existence of basic know how of powerful POINTERS. – Nik Oct 27 '14 at 10:34
  • 3
    In C, you don't cast the return value of malloc. See [c-faq 7.7b "What's wrong with casting malloc's return value? "](http://c-faq.com/malloc/mallocnocast.html) and [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Secondly, don't tag a question as both C++ and C unless your specific question pertains to both languages. –  Oct 27 '14 at 10:37
  • Thank you hagubear, I understand, because malloc returns a void pointer. – Michael Oct 27 '14 at 10:40

2 Answers2

1

This is a pointer cast: it changes the void* return from malloc (a generic pointer) to an item* (a pointer of the specific type you need). A void* is a pointer that can point to anything, but you can't do any useful operations on it like indirection and arithmetic.

That said, the cast is useless and considered bad practice, because the C language guarantees that a void* will be converted to the right type automatically once you assign it. Just

curr = malloc(sizeof(item));

will do the trick and is less error-prone.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

The (item *) part is a type name (item * means "pointer to item") in parentheses, so it's a type cast.

They are used to convert between types, and should never be used with malloc()'s return value like this.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606