>> DAVID J. MALAN: So it turns out that copying a string is not nearly as
simple as copying a primitive, like an int or a float.
After all, underneath the hood a string is a sequence characters.
So copying a string, therefore, has to involve copying that whole sequence of
characters.
>> Let's turn our attention back to that last implementation and rip out this
line, string t equals s, which clearly wasn't sufficient.
Let's replace it with a line that looks, instead, like this.
String t gets malloc of string length of s plus 1 times the size of a char.
>> Now there's quote a bit going on in this line of code.
First, malloc, short for memory allocation, and the
function does just that.
Given an integer, it returns to you the address of a chunk of memory of
that many bytes.
Meanwhile, the string length of s plus 1 is meant to indicate that we want as
many bytes as s already occupies, including its null terminator, the
backslash 0 at the end of a string.
>> Meanwhile, I don't necessarily remember how big a char is, even
though on most systems it's simply 1 byte, so I'll call size of char to
figure out dynamically how big an individual character is.
Once multiplied together, I get back the total number of bytes that I need.
>> But what if malloc fails to return the memory we need?
I'd best check for that as follows.
If t equals null, then I'm first going to free s, the memory returned by get
string, and then I'm going to return 1, to signify error.
>> But if all is well, I'm going to proceed to use a four loop and iterate
as follows.
For int i get 0, n equals the string length of s.
I'm going to do this so long as i is less than or equal to n so that I
iterate up through and including the null terminating character in s.
>> And on each iteration, I'm going to increment i.
Meanwhile, inside of this loop, copy s's i-th character into t's i-th
location, it suffices to do t bracket i gets s bracket i.
>> Let's now save, compile, and run this new program.
Make copy 1 dot slash copy 1.
And I'll say something like hello in all lowercase.
And thankfully, this time my original remains unchanged.
hello in all lowercase.
But the copy is, indeed, capitalized.