3

Assuming list is some structure

list *temp;
temp = new list;

the above is in c++, does this have an equivalent in C?

  • There are no real ways to achieve this because c is not object oriented so you cannot have constructors but you can create functions that initialize structs and return its pointer as a contructor would – midugh Oct 13 '19 at 21:14
  • 1
    In C, I'd do it this way: `list* temp; temp = malloc(sizeof(list)); list_init(temp);` – Eljay Oct 13 '19 at 21:17
  • I like `list *temp = malloc(sizeof *temp);`. That way if you ever change it from a list to something else, there's less code to change, and it's in general less error prone. – Shawn Oct 13 '19 at 21:34

1 Answers1

5
list *temp;
temp = malloc(sizeof(list));

[...]

free(temp);

C doesn't have the new keyword - you've got to allocate and free the memory you'd like to use manually. new also does some work behind the scenes, like calling constructors and returning the proper pointer type - malloc doesn't cover that, and has to be handled by the programmer.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37