Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between methods to create a character array

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?

like image 552
ShanZhengYang Avatar asked Sep 18 '26 01:09

ShanZhengYang


1 Answers

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

  1. we may forget to reserve the space for null-terminator \0.
  2. we may supply an initializer string more than that of the size specified.

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.

like image 167
Natasha Dutta Avatar answered Sep 19 '26 19:09

Natasha Dutta