2

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?

2
  • 1
    There's no difference between the two. Commented Jun 5, 2015 at 13:08
  • Except that the first one's size is redundant and a maintainance burden. Commented Jun 5, 2015 at 13:50

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

8 Comments

@Olaf Agree. It's kind of less-headache when left to compiler, isn't it? :-)
@Olaf Right, +1ed. I myself expanded my answer a bit, too. :-)
The edit is wrong for the specific example where the actual length is 11 anyway. It would apply if the size of the array was larger than the string.
@PavelŠimerda I really did not understand your point. How this is wrong? We don't know about the intended use of the array now, do we?
Both ways create an array of eleven bytes. Therefore none of them can be used for storing longer strings. Therefore the limitation applies to both ways equally unless you replace eleven with a higher number. You would have to do char entireName[100] = "John Smith" instead and then store names up to 99 characters (up to 100 bytes including NUL).
|
3

The two versions are basically identical as given in the question.

However, as the array is not const, you apparently intend to change it, so the string literal is just to initialize it. In this case, giving the maximum size for the array should strongly be considered.

The size allocated is the same for both cases of this example (the compiler calculates the size from the string literal and appends '\0').

However, if you you intend to store a longer string into the array later, the version char entireName[] = "John Smith"; will result in _undefined behaviour(UB, **anything** can happen). This because the compiler only allocates the size required by the string literal (plus'\0'), but does not know you need more during execution. In theses case, always use the explicit form[]`.

Warning: If the size of the string literal exactly matches the given size of the array, you might not be warned (tested with gcc 4.8.2 -Wall -Wextra: no warning) that the implictit '\0' cannot be stored. So, use that with caution! I suspect some legacy reasons for this being legal (it was in pre-ANSI K&C-C actually), possibly conserve RAM or packing. However, if the string litera as given does not fit, gcc does warn, if you enable most warnings (for gcc, see above).

For a const array always use the second version, as that is easier and even more explicitly stating that you want the size of the given string literal. Without being able to change the value lateron, nothing is gained in giving an explicit size, but (see above) some safety is lost.

Comments

3

There's no difference between the two as you specify the same size that the compiler would allocate otherwise.

However, if you explicitly specify the size and is less than the size of the string literal that you intend to copy, for example,

char entireName[8] = "John Smith"; 

then only 8 chars will be copied and rest will be discarded and there won't a 0 terminator either. This is not what you would want to do in most cases. For this reason, it's always better to let the compiler do it.

3 Comments

So, because the compiler doesn't know the exact size required, the second expression should be slower, right?
Compiler always has the knowledge about string literals as they typically go into data section (have static storage duration), they could always calculate the length. It could be slower but only the compile time.
Compiler knows all the sizes here — it was compiler that parsed your literal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.