在程序中定義字符串
一、字符串常量(或者稱之為字符串文字)
1.介紹
字符串常量(string constant),又稱為字符串文字(string literal),是指位于一對雙引號中的任何字符。
雙引號中的字符編譯器會自動提供結束標志\0字符,作為一個字符串被存放在內存里面。
如:
#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會將其串聯起來。
例如:
char greeting[50] = "Hello, and" "how are" "you" "today!";
相當于
char greeting[50] = "Hello, and how are you today!";
2.使用雙引號
如果想在字符串中間使用雙引號,可以在雙引號的前面加一個反斜線符號。
如:
printf ("\"Run, Spot,run!\"\n");
3.字符串常量
字符串常量屬于靜態存儲(static storage)類。
靜態存儲指的是如果在一個函數中使用字符串常量,即使是多次調用了這個函數,該字符串在程序的整個運行過程中只存儲一份。整個引號中的內容作為指向該字符串存儲位置的指針。
#include <stdio.h>
int main (void)
{
printf ("%s, %p, %c \n", "We", "are", *"space farers");
return 0;
}