You can use realloc
to try to resize a previous allocation. It does not work on arbitrary pointers, such as your str1 = "hello"
† – you need to allocate the initial area with, e.g., malloc
. It may also end up allocating a new area at a different address (and copying the contents of the old area there), i.e., you must update all pointers that refer to the old area to point to the new area returned by realloc
.
If these constraints are not acceptable, you are out of luck and need to design your program in some other way (e.g., set a maximum length and reserve that much space to begin with, then just use as much as you need).
† Also note that string literals, such as "hello"
, are not modifiable to begin with. The typical way around this is to use an array instead, e.g., char str1[] = "hello"
, but that can't be resized either. (But you could specify a larger size for it than needed for its initial contents if you know you will be storing a longer string there later.)