I am taking an open online course CS50 from Harvard. The last lecture I had was about memory allocation and pointers (two concepts which are absolutely new to me).
- Is in the code snippet above c also a pointer of type char*?
No it is not. It is an array of ten char.
However, the name of an array can, when used in a context where a pointer is expected, be converted to a pointer, and therefore effectively used as if it is a pointer.
- Does char c[10] also reserve memory on the heap as malloc does?
No. Heap and stack are not completely accurate terms either, but I won't expand on that further.
What malloc() does is called "dynamic memory allocation" according to the standard.
The behaviour of char c[10]; depends on context.
{}) it creates an array of automatic storage duration. That array ceases to exist, as far as your program is concerned, when the scope is exited (e.g. if the function returns).
- Are the ways to allocate memory equivalent?
Nope.
char c[3] = "aaa";free(c); returns a runtime error; so it seems I can not free the memory I have allocated with char c[3]. Why is that?
Because free() only has defined behaviour when passed a pointer to dynamically allocated memory - i.e. returned by malloc(), calloc(), or realloc() or a NULL pointer (which causes free() to do nothing).
c is an array of either static or automatic storage duration, depending on context, as I mentioned above. It is not dynamically allocated, so passing it to free() gives undefined behaviour. A common symptom of that is a runtime error, but not the only possible symptom.