I was wondering if there is any difference (in terms of syntax and performance) between a string defined like
char str[200];
and
char *str;
str = calloc(200, sizeof(char));
Are there differences in terms of usage? (for ex, one is not compatible with strncpy
or something) And more importantly, are there differences in terms of performance?
EDIT: I understand that an array defined by char *
and calloc
can grow and shrink, but should I pick heap memory over stack memory or the other way around for any reason? That's what I was really trying to ask.
char str[200]
allocated in stack memory where ascalloc()
allocates in heap memory.By nature of calloc(), it assigns 0 to all the bytes allocated by it.
Pls refer the following for stack and heap comparison
Which is faster: Stack allocation or Heap allocation
http://www.linuxquestions.org/questions/programming-9/stack-faster-than-heap-685004/
What and where are the stack and heap?
I am surprised that no one mentioned that first str i.e. array name evaluates to a constant pointer and cannot be reassigned, where as the second one is a pointer variable which can be reassigned.
So
Once you create the string, there is no difference in usage.
char str[100] allocates the string on stack, while the other approach uses heap. Allocations on stack are always faster than on heap (see this discussion: Which is faster: Stack allocation or Heap allocation)
Additionally, calloc() sets all elements of an array to 0/NULL, lowering the performance even further. If you program in C++ and need to use heap, always write:
char *str = new char[200];
This has additional benefits, e.g. raising an error if the heap is full.
First, allocates memory on stack, while second allocates dynamic memory. stack memory is auto managed while dynamic memory needs manual management.
When you have a choice, You should always prefer the first:
In terms of usage with functions both are similar, in simple sense while using with functions both are pointers which point to a consecutive blocks of memory. When you pass a array to function, it decays as pointer to first element.
Difference is where they are stored and whether they are auto managed or manually managed.
You should use stack allocation whenever possible: it is easier to maintain for the programmer and it is also less demanding performance-wise.
There are many cases where array stack allocation is not possible.
Also note that
char str[200]
“knows” its size (i.e.sizeof(str) == 200*sizeof(char)
) whereas you’ll have to memorise the size of the allocated array in a auxiliary variable to work with it (sizeof(str) == sizeof(char*)
, typically 4 or 8).Char array memory is allocated on stack . as soon as control moves out of function containing the array , the memory is deallocated and array can't be accessed now.
While calloc function allocates memory on heap and remains till program is in in execution or memory is deallocated manually