Difference between Character Array and a String

Vranda Agarwal
3 min readJan 1, 2021

--

When we put our step into a new field, we always try to explore new things and love to discover new data.

Same is with programming languages like C, C++, and Java etc. While searching or reading about char arrays and strings, mostly a question arises that what is the difference between the two? The answer is — a char array is just a sequential collection of characters and on the other hand, a string is a class that contains char array.

After reading this, the same question again arises. So, what is the real difference then?

Here are some key points :

· Memory allocation :

While declaring an array we have to first declare its size. If char array is allocated on stack then it will occupy the space of 128 bytes, irrespective of the input size of str i.e. the length of array is fixed. And if the size of input exceeds from 128 characters then it will crash and provide undesired results. But a string automatically manages it for us and there is no need to declare its size beforehand.

· Length count : To determine the length of an array, it has to be scanned character by character. But a string knows its length without counting.

· Mutable and Immutable: Arrays are mutable which means their field or data can be modified by the use of their indices but the strings are immutable which implies that the data in a string cannot be changed if once initialized.

Now, have a look on the syntax of string initialization :

char* s=”String Syntax”;

Here, only one pointer is required to refer the whole string. And no need to declare its size in advance.

This syntax will finely work in C but in C++ it will create a problem because in C string literals are arrays of char and in C++, string is constant array of char.

const char* s=”String Syntax”;

So, in C++, use a const keyword before char*.

Now, we think about what to prefer, a character array or a string?

Both have their own importance which depends on the need of the program.

Importance of string :

Only one pointer is required to refer a string and it is also not necessary to declare its size earlier so it is more memory efficient than character array.

C++ strings can contain embedded \0 characters and they know their length without counting. So, they are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they’re more readable and easier to use.

Importance of character array :

Arrays can be recommended as strings are immutable in nature.

Character arrays are preferred over string for passwords. With an array, you can explicitly wipe the data after you’re done with it. You can overwrite the array with anything you like, and the password won’t be present anywhere in the system, even before garbage collection.

Thanks for reading! Don’t forget to clap for this tutorial if you liked it and I’d also love to know what you think.

--

--

No responses yet