Post by Omar RadwanI'm a beginner C programmer, it's my first programming language. Honestly,
I think I chose the right language.
That feeling probably won't last. C makes a *lousy* teaching language. It's
a great systems and app programming language, but as a first language, it
has more than its share of flaws.
Post by Omar RadwanAll the other languages have something that I don't agree with. But a
int arr[] = malloc((sizeof(int)) * 8);
That should be
int *arr = malloc...;
instead of
int arr[] = malloc...;
"malloc" returns a pointer value, so "arr" has to be declared with a pointer
type (arrays and pointers are *not* the same thing).
A preferred way of writing that would be
int *arr = malloc( sizeof *arr * 8 );
The expression "*arr" has type "int", so "sizeof *arr" will return the same
value as "sizeof (int)". This way, If you ever change the type of "*arr"
(say from "int" to "long"), then you only have to make the change in one
place.
There are two reasons why you would do this.
1. You don't know how many elements you need until runtime;
2. You want to create a *really big* array.
You won't always know that you need to set aside 8 (or 10, or 100, or whatever)
elements in the array ahead of time, or the array may need to grow or shrink
as the program runs. Using dynamic memory allocation means you can set aside
exactly the amount of memory you need based on runtime inputs.
The pool of memory for auto variables (aka the stack) may be fairly limited,
and trying to declare *very large* arrays (megabyte or larger) at block scope
may lead to a runtime error. The dynamic memory pool (aka the heap) is typically
much larger, and it allows you to (potentially) set aside *very large* blocks
of memory.
C99 introduced variable-length arrays. Unlike regular arrays, their size isn't
established until runtime, like so:
int size = some_value();
int arr[size];
Like regular arrays, memory for VLAs is allocated from the stack, so like
regular arrays they can't be used for *very large* objects. They cannot be
used as struct members, nor can they be declared "static" or appear outside
of a function.
Also, VLA support has always been a little spotty, and as of the 2011 standard
they are optional, so you can't always count on them being available. They can
be *very* useful in some circumstances, though.
Post by Omar Radwantypedef struct Person
{
int age;
float height;
float weight;
char name[];
};
struct Guy Bobby = malloc(sizeof(Guy))
should be
struct Guy *Bobby = malloc( sizeof *Bobby );
Post by Omar Radwanwhen someone could just call it in as
struct Guy Bobby;
Same deal; you don't know how many structs you need until runtime, or you need
to allocate a *very large* object.
Once you start learning about basic data structures like lists and trees,
you'll start to see where and how dynamic memory comes in to play (you don't
*need* dynamic memory to implement those structures, but it makes life a lot
easier).