Possible Duplicate:
Difference between declaration and malloc
Is there a difference between these two programs?
int main(void) {
char str[80];
}
and
int main(void) {
char * str = (char*) malloc( sizeof(char) * 80 );
}
So is there a difference between using malloc and the array-like syntax? So if I need memory for 80 characters, I should use malloc and not the other possibility, right?
I’ll try to answer my own question!
allocates 80 bytes on the stack. This will be automatically reclaimed when
strgoes out of scope.allocates 80 bytes on the heap. This memory is available until you call
free.Note that the second case can be simplified to
i.e. You should not cast the return from
mallocin C andsizeof(char)is guaranteed to be 1