String literals

If you were dealing with C strings a lot, malloc’ing the memory and stuffing the characters in one-by-one would be a real pain. Instead, you can create a pointer to a string of characters (terminated with the zero character) by putting the string in quotes. Change your code to use a string literal:

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​c​h​a​r​ ​x​ ​=​ ​'​!​'​;​ ​/​/​ ​T​h​e​ ​c​h​a​r​a​c​t​e​r​ ​'​!​'​

 ​ ​ ​ ​w​h​i​l​e​ ​(​x​ ​<​=​ ​'​~​'​)​ ​{​ ​/​/​ ​T​h​e​ ​c​h​a​r​a​c​t​e​r​ ​'​~​'​
 ​ ​ ​ ​ ​ ​ ​ ​p​r​i​n​t​f​(​"​%​x​ ​i​s​ ​%​c​​n​"​,​ ​x​,​ ​x​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​x​+​+​;​
 ​ ​ ​ ​}​

 ​ ​ ​ ​c​h​a​r​ ​*​s​t​a​r​t​ ​=​ ​"​L​o​v​e​"​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​%​s​ ​h​a​s​ ​%​z​u​ ​c​h​a​r​a​c​t​e​r​s​​n​"​,​ ​s​t​a​r​t​,​ ​s​t​r​l​e​n​(​s​t​a​r​t​)​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​T​h​e​ ​t​h​i​r​d​ ​l​e​t​t​e​r​ ​i​s​ ​%​c​​n​"​,​ ​s​t​a​r​t​[​2​]​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build it and run it.

Notice that you don’t need to malloc and free memory for a string literal. It is a constant and appears in memory only once, so the compiler takes care of its memory use. As a side-effect of its constant-ness, bad things happen if you try to change the characters in the string. Add a line that should crash your program:

 ​ ​ ​ ​c​h​a​r​ ​*​s​t​a​r​t​ ​=​ ​"​L​o​v​e​"​;​
 ​ ​ ​ ​s​t​a​r​t​[​2​]​ ​=​ ​'​z​'​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​%​s​ ​h​a​s​ ​%​z​u​ ​c​h​a​r​a​c​t​e​r​s​​n​"​,​ ​s​t​a​r​t​,​ ​s​t​r​l​e​n​(​s​t​a​r​t​)​)​;​

When you build and run it, you should get a EXC_BAD_ACCESS signal. You tried to write into memory that you are not allowed to write in.

To enable the compiler to warn you about writing to constant parts of memory, you can use the const modifier to specify that a pointer is referring to data that must not be changed. Try it:

 ​ ​ ​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​s​t​a​r​t​ ​=​ ​"​L​o​v​e​"​;​
 ​ ​ ​ ​s​t​a​r​t​[​2​]​ ​=​ ​'​z​'​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​%​s​ ​h​a​s​ ​%​z​u​ ​c​h​a​r​a​c​t​e​r​s​​n​"​,​ ​s​t​a​r​t​,​ ​s​t​r​l​e​n​(​s​t​a​r​t​)​)​;​

Now when you build, you should get an error from the compiler.

Delete the problematic line (start[2] = 'z';) before continuing.

You can use the escape sequences mentioned above in your string literals. Use a few:

 ​ ​ ​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​s​t​a​r​t​ ​=​ ​"​A​ ​b​a​c​k​s​l​a​s​h​ ​a​f​t​e​r​ ​t​w​o​ ​n​e​w​l​i​n​e​s​ ​a​n​d​ ​a​ ​t​a​b​:​​n​​n​​t​​​"​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​%​s​ ​h​a​s​ ​%​z​u​ ​c​h​a​r​a​c​t​e​r​s​​n​"​,​ ​s​t​a​r​t​,​ ​s​t​r​l​e​n​(​s​t​a​r​t​)​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​T​h​e​ ​t​h​i​r​d​ ​l​e​t​t​e​r​ ​i​s​ ​​'​%​c​​'​​n​"​,​ ​s​t​a​r​t​[​2​]​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build and run it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset