What do you mean?
The C language does not have a specific string type, but it can also handle strings. This article does not discuss the use of strings, but rather discusses the relationship between C strings. Title, in c language code, if define # define STR = "Programming", and then use printf ("%s", "Programming"), what do these two "programming" have in common? Beginners may think this is just the content. In fact, that's true, but they have other "hidden secrets", what is it?
Let's practice!
First, let's take a look at the code:
1#include <stdio.h>2 3 #defineSTR "Programming"4 5 intMainvoid)6 {7printf"STR%s (%p\n",str,&STR);8printf"!!!%s (%p\n","Programming","Programming");9 getch ();Ten return 0; One}
%p represents the content (address) of the output pointer, and if the compiler does not support%p, replace the%u,%lu or% #x.
This code runs after TDM-GCC 4.8.1 is compiled:
After Visual C + + 2010 is compiled:
What do we get from this example?
In the example we can see that the address of the two string is the same!!! My view is this: The compiler does this to save memory space. C Primer Plus holds the view that "the compiler can store the same literal (constant) used multiple times in one or more places." To be sure, most compilers now support storing them in one place. The above code is compiled with TC on another computer, and the result is the same address. This might have been the case a long time ago, because the memory capacity was small.
This illustrates a problem: if you use pointers when manipulating strings, changing strings with pointers can cause other identical strings to change, because pointers save only addresses, do not copy content, and manipulate static store strings. So, C Primer Plus recommends that you use arrays to handle strings because the array uses dynamic storage space, which copies the original strings in the static store. If you must handle the string with pointers, it is recommended that you:
const char * PCH
Prevent changes to content that should not be changed.
"Programming" and "programming" are the same "programming"?