could you explain what's happening here
(char *) malloc(n * sizeof(char));
The malloc thing allocates the structure on the heap.
Think of it like this:
Anything you declare like char[] without calling malloc is memory that is released as soon as the function returns. Any memory you get by using malloc is never released unless you explicitly call free on it.
I know it's confusing, but you'll figure it out.
and what does (char *) do here
The (char *) bit does explicitly casts the pointer in the eyes of the compiler. It is a pointer to the start of memory that contains god knows what.
If you allocated sizeof char
then you would have a pointer to a block of memory that is the size of a single char
, which would be equivalent to an array of characters of size 1.
does C have array index oob error? I remember it took me days to find out that I've made a mistake while looping the array
No and yes.
Yes that can cause your program to segfault or maybe crash in some way.
No you don't get a named error that tells you what you messed up.
If you want to get some output it might be educational to make your own "data structure" and printf
or something if an error happens.
If you want C perf and sensible errors try Rust, but my Spidey Senses tell me you are still learning in general so that's not really a productive jump.