it has a much smaller overhead than vectors and new/delete and non C-style strings |
No it doesn't. Whoever is telling you that is lying to you.
Yes there is more code behind vector and string -- but if you don't use them you'll just have to write that code yourself. So you'll end up with the same thing, only you had to do a bunch of extra work and you'll have more bugs.
In fact... C++'s string class is actually
faster for some operations (like finding the length and concatenating) than the C strlen/strcat functions.
I know it's more 'C' like, but I want to learn that part, |
okay okay.
I'm open for knowledge -- but please note that you should never, ever, ever be writing this in C++. This is C code:
malloc is type unaware so the size you give it has to be the number of bytes you want to allocate. sizeof() can give you the size of one element in an array, so you'll need to multiply that with the number of elements you want.
Also... malloc cannot return an array because it doesn't know it's allocating an array -- it's just allocating a clump of memory. Therefore, it'll return a pointer which contains the address of the memory it just allocated for you. You would assign this to a Person pointer, so that you can use it as an array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
typedef struct
{
int age;
float height;
char *name;
} Person;
// if we want an array of 10 Persons:
Person* people = malloc(
sizeof(Person) // <- the size of 1 person
* 10 // <- we want room for 10 people
);
// now 'people' can be treated like an array of 10 people
people[0].name = malloc( sizeof(char) * 20 ); // allocate room for a string of length 19 (plus the null)
strcpy( people[0].name, "BillyBob" ); // set the name to BillyBob
people[0].height = 1.5f;
people[0].age = 15;
//////////////////
// Don't forget to clean up when you're done. Unlike with string and vector, this is not
// done automatically.
//
// If you do not do this, you will leak memory, and your program will consume more and more
// and more memory as it runs
//
// EVERY malloc must have a matching free. No exceptions.
// In the above example, there were 2: 1 for BillyBob's name
// and another for the array:
free(people[0].name); // clean up BillyBob's name
free(people); // then the array
|
Note again that malloc and free will fail catastrophically and possibly cause your program to crash if you are using complex types (classes) which is why you should never use these functions in C++.