CodeNewbie Community 🌱

Christopher Cooper
Christopher Cooper

Posted on

"new" keyword in C

Is the "new" keyword used in C?

Example of use in C++:

struct Person* ron = new Person;

Top comments (2)

Collapse
 
djuber profile image
Daniel Uber • Edited

I think the answer is no - new in C++ is used for classes and structs to initialize a new instance, C has structs (only), and you declare them like any other variable type.

struct Person jon; // local variable - stack allocated
struct Person* ron = (struct Person *) malloc( sizeof( struct Person )); // pointer to struct - heap allocated
Enter fullscreen mode Exit fullscreen mode

You can see the struct Name gets repeated a lot, it's normal to use a typedef in that situation to make that shorter, usually in the header:

typedef struct Person {
  // structure members go here as normal
} Person;
Enter fullscreen mode Exit fullscreen mode

There is also support for initializing the members during the definition (if you search for "designated initializer" that's probably the standard name for this):

struct Person {
  char name[40];
  unsigned int age;
};

int main() {
  struct Person jon = { name: "John", age: 10};
  struct Person joe = { .name="Joe", .age=20 };
  struct Person jane = { "Jane", 30 };
}
Enter fullscreen mode Exit fullscreen mode

new and delete work around a lot of the chores of using malloc and free, but are C++ only.

Collapse
 
chriscyork profile image
Christopher Cooper

Thanks Daniel, this is a really big help for me. Thanks for including the method for doing it properly too!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.