The simplest approach is to pre-allocate enough memory in your array to hold the longest string you expect to store in it.
An array is a region of storage; it has a size (number of elements) that's fixed at the point where it's created. You can't expand an existing array -- though you can use realloc
to replace an array by a longer one.
A string is a sequence of characters up to and including a terminating '\0'
null character.
An array may contain a string -- and the length of the string is not the same thing as the size of the array.
Note that the length of a string does not include the terminating '\0'
; `"hello" has a length of 5 and a size of 6.
Your declaration:
char a[] = "stackoverflow";
causes the compiler to create a
with a size just big enough to hold the string used to initialize it. It's equivalent to:
char a[14] = "stackoverflow"; /* 13 characters + 1 for the '\0' */
You can shorten the string stored in the array a
, but it can't hold a string with a length greater than 13:
strcpy(a, "STACK");
After this, the array a
is still 14 characters in size (that never changes), but its contents are now:
"STACK\0verflow\0"
but anything after the first '\0'
will probably be ignored.
If you anticipate storing a longer string, you can create it with a larger size:
char a[100] = "stackoverflow";
strcat(a, " is fun!";
This approach can be both wasteful (the array is likely to be bigger than it needs to be at the moment) and error-prone (it's difficult to avoid overflowing the array bounds by storing an overly long string in it). But if you're sufficiently careful, it can be good enough.
There are some string manipulation functions that make it easier to avoid overflowing your array. strncat
is a safer version of strcat
that lets you specify the size of the target array. There are also some non-standard functions like strlcpy
and strlcat
.
(strncpy
, however, is not recommended.)
Other approaches are possible. For example, you can dynamically allocate memory space using malloc()
, and reallocate it (replacing your array by a larger or smaller one) using realloc
. You still have to be careful not to read or write past the end of an array -- and you have to keep track of the array size yourself. It's a more flexible approach, but it imposes more overhead, both on the performance of your program and on you as a programmer.
C (unlike C++, BTW) doesn't have a simple mechanism for managing strings of varying lengths. The C string facilities, in some cases, are what higher-level mechanisms are built on top of.