Bifalgorithm post · Computer science one · Character Arrays
How do you dynamically allocate and copy strings in C?
How do you dynamically allocate and copy strings in C? (Computer science one · Character Arrays) — "Just as with int and double types, however, we can dynamica…
Ideas in this flowchart
- Dynamic allocation of character arrays requires special string-handling rules
- Character memory can be dynamically allocated with malloc(), just like int and double memory
- At least one extra character must be allocated for the null-terminating character
- The example allocates space for 10 characters
- Because of the terminator, the array can hold only 9 characters of text
- An entire string cannot be assigned directly to the dynamically allocated array
- The assignment fullName = "Tom Waits"; is the wrong approach
- The assignment makes fullName point to the static literal string
- The original dynamically allocated array is lost, causing a memory leak
- strcpy() must be used to copy a string into the allocated array
- The function prototype is char *strcpy(char *dest, const char *src);
- strcpy() copies the source character sequence into the destination