在程序中定義字符串
一、字符串常量(或者稱之為字符串文字)
1.介紹
字符串常量(string constant),又稱為字符串文字(string literal),是指位于一對(duì)雙引號(hào)中的任何字符。
雙引號(hào)中的字符編譯器會(huì)自動(dòng)提供結(jié)束標(biāo)志\0字符,作為一個(gè)字符串被存放在內(nèi)存里面。
如:
#define MSG "You must have many talents.Tell me some."
printf ("Hi! I'm Clyde the Computer." "I have many talents.\n");
char greeting[50] = "Hello, and how are you today!";
如果字符串文字中間沒有間隔或者間隔的是空格符,ANSI C會(huì)將其串聯(lián)起來。
例如:
char greeting[50] = "Hello, and" "how are" "you" "today!";
相當(dāng)于
char greeting[50] = "Hello, and how are you today!";
2.使用雙引號(hào)
如果想在字符串中間使用雙引號(hào),可以在雙引號(hào)的前面加一個(gè)反斜線符號(hào)。
如:
printf ("\"Run, Spot,run!\"\n");
3.字符串常量
字符串常量屬于靜態(tài)存儲(chǔ)(static storage)類。
靜態(tài)存儲(chǔ)指的是如果在一個(gè)函數(shù)中使用字符串常量,即使是多次調(diào)用了這個(gè)函數(shù),該字符串在程序的整個(gè)運(yùn)行過程中只存儲(chǔ)一份。整個(gè)引號(hào)中的內(nèi)容作為指向該字符串存儲(chǔ)位置的指針。
#include <stdio.h>
int main (void)
{
printf ("%s, %p, %c \n", "We", "are", *"space farers");
return 0;
}