一、char型別陣列和null字符
- 字串都是被存盤在char型別陣列里面,字符被存盤在相鄰的存盤單元中,每個單元存盤一個字符,
- 每個字串末尾會有一個
\0,這就是空字串,C語言用它來標記字串結束,空字串不是數字0,他是非列印字符,其ASCII碼是0, - 陣列定義:同型別的資料元素的有序序列,
1.使用字串
#include<stdio.h>
#define PARISE "You are an extraordinary being"
#pragma warning(disable:4996)
int D16_1_praisel(void) {
char name[40];
printf("What's your name?");
scanf("%s", name);
printf("Hello,%s. %s\n", name, PARISE);
return 0;
}
運行顯示:

- 編譯器會自動給字串的末尾添加空字符
\0
注意點:我們在進行輸入名字的時候是兩個單詞的時候,比如:Lebron James,那么
scanf()會讀取空格之前的第一個單詞,不會讀取后面的單詞,也可以使用方法fgets()后面再介紹,
2.strlen()函式
sizeof運算子,它以位元組為單給出物件的大小,strlen()函式給出字串中的字符長度,因為1位元組存盤一個字符二者結果可能相同,但本質并不是一種計算方式,
#include<stdio.h>
#include<string.h> /*提供strlen()函式的原型*/
#define PRAISE "You are an extraordinaty being."
#pragma warning(disable:4996)
int D16_2_praise2(void) {
char name[40];
printf("What's your name?");
scanf("%s", name);
printf("Hello,%s.%s\n", name, PRAISE);
printf("Your name of %zd letters occupies %zd memory cells.\n", strlen(name), sizeof(name));
printf("The phrase of praise has %zd letters ", strlen(PRAISE));
printf("and occupise %zd memory cells.\n", sizeof PRAISE);
return 0;
}
運行顯示:

注意點:
(1)如果使用ANSI C之前的編譯器,必須要移除這一行:#include<string.h>;之前的編譯器使用的是strings.h這個頭檔案;
(2)C99和C11標準專門為sizeof運算子的回傳型別特地添加了%zd轉換說明,對于函式strlen()也同樣適用,早期的C需要使用實際的回傳型別(通常是unsigned或unsigned long)
(3)sizeof后面接括號的問題,如果是變數或者字面量,括號可有可無;如果是型別則需要括號,這里推薦都使用括號為好,
二、原始碼:
- D16_1_praisel.c
- D16_2_praise2.c
- https://github.com/ruigege66/CPrimerPlus/blob/master/D16_1_praisel.c
- https://github.com/ruigege66/CPrimerPlus/blob/master/D16_2_praise2.c
- CSDN:https://blog.csdn.net/weixin_44630050
- 博客園:https://www.cnblogs.com/ruigege0000/
- 歡迎關注微信公眾號:傅里葉變換,個人賬號,僅用于技術交流

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/3624.html
標籤:C
下一篇:LinuxKernel(一)
