I am curious about the different methods to create a character array in C. Let's say we want to create a character array holding the string "John Smith". We could either initialize the array by supplying the number of elements explicitly, i.e.
char entireName[11] = "John Smith";
where there are four spaces for characters J-o-h-n, one for the space, five for S-m-i-t-h, and one for the string terminator \0.
You could also do the above by simply typing
char entireName[] = "John Smith";
Will there be a large difference in who these two character arrays are compiled? Is the same amount of memory allocated for the two expressions, and executed at the same speed?
What really is the difference?
Both are same, but the second one is advisable.
In case you're leaving out the size of the array during definition and initialization, the compiler will allocate proper size required. This is less error prone, compared to the definition with a fixed size as sometimes
\0.The fact remains, with proper warnings enable, you'll get an warning if you do the above, but with the second approach, theses scenarios will not arise, so less worries.
EDIT:
FWIW, in the second scenario, the array length will be decided based on the supplied initializer string length. As we know, compiler time strings cannot be resized at runtime, so that's the only possible limitation of the second approach. If, at a later part, you want the array to hold something bigger than that of the supplied initializer string, the second approach is not suitable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With