標籤:char rom 編譯器 col === 字元數組 長度 rcp class
//一級指標的典型用法
//數組 int a[10]
//字串
//1 C語言的字串 以零結尾的字串
//2 在C語言中沒有字串類型 通過字元數組 來類比字串
//3 字串的記憶體配置 堆上 棧上 全域區 (很重要)
字串的初始化
void main(){ //1 指定長度 char buf2[100] = {‘a‘, ‘b‘, ‘c‘, ‘d‘}; //1-1 char buf3[2] = {‘a‘, ‘b‘, ‘c‘, ‘d‘}; //如果初始化的個數大於記憶體的個數 編譯錯誤 //1-2 //後面的buf2[4]-buf2[99] 0 //2 不指定長度 C編譯器會自動幫程式員 求元素的個數 char buf1[] = {‘a‘, ‘b‘, ‘c‘, ‘d‘}; //buf1是一個數組 不是一個以0結尾的字串 printf("buf2: %s \n", buf2); printf("buf2[88]:%d \n", buf2[88]); printf("hello....\n"); system("pause"); return ;}
//下面要是面試題可別錯//用字串 來 初始化字元數組//strlen() 長度 不包括0//sizeof() 記憶體塊的大小void main52(){ int size = 0; char buf3[] = "abcd"; // buf3 作為字元數組 應該是5個位元組 //作為字串 應該4個位元組 int len = strlen(buf3); printf("buf3字元的長度:%d \n", len); //4 //buf3 作為數組 數組是一種資料類型 本質(固定小大記憶體塊的別名) size = sizeof(buf3); // printf("buf3數組所佔記憶體空間大小:%d \n", size); //5 printf("hello....\n"); { char buf4[128] = "abcd"; // buf printf("buf4[100]:%d \n", buf4[100]); } system("pause"); return ;}
//通過數組下標 和 指標
void main58(){ int i = 0; char *p = NULL; char buf5[128] = "abcdefg"; // buf for (i=0; i<strlen(buf5); i++) { printf("%c ", buf5[i]); } p = buf5; //buf 代表數組首元素的地址 for (i=0; i<strlen(buf5); i++) { p = p +i; //*(p+i) printf("%c ", *p ) ; } //buf for (i=0; i<strlen(buf5); i++) { printf("%c ", *(buf5+i) ) ; } //[] *的推導過程 // buf5[i] ===> buf5[0+i]; ==> *(buf5+i); { //buf5 = buf5 + 1; //buf5 = 0x11; } printf("hello....\n"); system("pause");}// []的本質 :和*p 是一樣 ,只不過是符合程式員的閱讀習慣// buf5 是一個指標, 唯讀常量 buf5是一個常量指標 析構記憶體的時候,保證buf所指向的記憶體空間安全釋放//為什麼這麼做?//p普通指標和記憶體首地址區別
//一級指標的記憶體模型void main61(){ char buf[20]= "aaaa"; //定義並且初始化 char buf2[] = "bbbb"; char *p1 = "111111"; char *p2 = malloc(100); strcpy(p2, "3333"); system("pause"); return ;}
//字串技術推演void copy_str(char *from, char *to){ for (; *from != ‘\0‘; from++, to++) { *to = *from; } *to = ‘\0‘; return ;}void main(){ char *from = "abcd"; char buf[100]; copy_str(from, buf); printf("buff:%s\n", buf); system("pause");}
字串、字串數組、與一級指標