C語(yǔ)言中 初始化一個(gè)字符串有兩種定義方式:
第一種為
char str[] = "hello"; 或者 char str[] = {'h','e','l','l','o','\0'};
第二種為
char *str = "hello";
兩種的區(qū)別如下:
- char str[] 將字符串定義為字符串變量 (可讀可寫(xiě))而 char *str 將字符串定義為字符串常量 (只讀)
#include <stdlib.h> int main() { char str1[] = "hello"; char m[] = "hello"; char *str2 = "hello"; char *n = "hello"; //str1[0] = 'p'; //str2[0] = 'l'; //printf("%s",str1); // 成功 //printf("%s",str2); // 錯(cuò)誤 寫(xiě)入訪問(wèn)權(quán)限沖突 printf("str1 = %p\n",str1); printf("m = %p\n",m); printf("str2 = %p\n",str2); printf("n = %p\n",n); return 0; }
程序運(yùn)行結(jié)果如下:
?可以看出字符串str1 與 m地址不同 ,說(shuō)明它們?cè)趦?nèi)存中開(kāi)辟了兩塊區(qū)域 是一種變量。而字符串str2與n地址相同,說(shuō)明它們指向同一塊區(qū)域 是字符串常量。
-
雖然char str1[] 定義str1為字符串變量,但是它的數(shù)組名代表指針常量不可以修改
#include <stdlib.h> int main() { char str[] = "ni chou sha"; while(*str) { // 遍歷字符串 打印每個(gè)字符地址 printf("%p\n",str); str++; // 報(bào)錯(cuò) 表達(dá)式必須是可修改的左值 } return 0; }
上述程序有誤 字符串名str實(shí)質(zhì)為指針指向字符串首地址,但是是一種指針常量 不能被修改!可以將程序改為
#include <stdlib.h> int main() { char str[] = "ni chou sha"; char *p = str; // 定義一個(gè)指針變量 用于指針操作 while(*p) { // 遍歷字符串 打印每個(gè)字符地址 printf("%p\n",str); p++; } return 0; }
或者
#include <stdlib.h> int main() { char *str = "ni chou sha"; while(*str) { // 遍歷字符串 打印每個(gè)字符地址 printf("%p\n",str); str++; } return 0; }
程序運(yùn)行成功! 結(jié)果如下:
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-400872.html
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-400872.html
到了這里,關(guān)于C語(yǔ)言字符串的兩種定義方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!