//初始化數組有兩種方法 //1 不指定長度 char buf[] = {'a', 'b', 'c'}; //buf是個指針 是個常量指針 //2 指定長度 char buf2[10] = {'a', 'b', 'c'}; //3 字符串和字符數組的區別 char buf3[] = {'a', 'b', 'c', '\0'}; //buf是個指針 是個常量指針 3 |
Memcpy()是內存塊拷貝,最後要手動加上’\0’,字符串拷貝strcpy()自動拷貝’\0’ memcpy(pOut, pBegin,n); |
//對於字符串分配內存有三種方式,可以在堆、棧、全局區(常量區),你要知道你的內存是怎麼分配的 char *buf1= " abcd11111abcd2222abcdqqqqq "; char buf2[] = " abcd11111abcd2222abcdqqqqq "; //一級指針的輸入模型 //沒有內存塊,哪有指針啊。。。 int trimSpace_很不ok的做法(char *mybuf)//如果人家傳buf1無法修改buf1,它分配在全局區是常量無法修改 { int count = 0; int i = 0, j = 0;
char *p = mybuf; j = strlen(p) -1;
while (isspace(p[i]) && p[i] != '\0') { i++; }
while (isspace(p[j]) && j>0) { j--; } count = j-i +1;
// printf("count:%d", count); //void * __cdecl memcpy(void *, const void *, size_t); memcpy(mybuf, mybuf+i, count); mybuf[count] = '\0'; return 0; //system("pause"); }
//一般情況下不要修改輸入的內存塊的值 int trimSpace_ok(char *mybuf, char *outbuf) { int count = 0; int i = 0, j = 0;
char *p = mybuf; j = strlen(p) -1;
while (isspace(p[i]) && p[i] != '\0') { i++; }
while (isspace(p[j]) && j>0) { j--; } count = j-i +1;
// printf("count:%d", count); //void * __cdecl memcpy(void *, const void *, size_t); memcpy(outbuf, mybuf+i, count); outbuf[count] = '\0'; return 0; //system("pause"); }
|
通過字符串常量初始化字符數組會自動添加\0 而通過字符數組不會 |
char p[4] = "abc"; //strlen(p)爲3 char p[8] = "abc\0 abc "; //strlen(p)爲3 char p[3] ={'a','b','c'}; //strlen(p)爲3 char p[6] ={'a','b','c', '\0','b','c',}; //strlen(p)爲3
/*1. 當 char buf[3]={'s','s','d'}時 將\0沖掉 printf("%d\n",strlen(buf)); 不確定多少,因爲會一直找\0 printf("%d\n",sizeof(buf)); 等於3 */ /* 2.當: char buf[4]={'s','s','d'}; printf("%d\n",strlen(buf)); 等於3 printf("%d\n",sizeof(buf)); 等於4 */ //如何通過指針獲取數組大小 double buf[6]={3.0,3.0,3.0,3.0,3.0}; double*p= buf; //printf("%d\n",strlen(*p)); //一個char型不能求字符串長度 printf("%d\n",sizeof(*p)); //可求數據類型大小 printf("%f\n",strlen(p));//錯誤值,如果是字符數組,可以求得數組長度 printf("%d\n",sizeof(p));//sizeof總是求得指針本身 printf("%f\n",strlen(buf));//錯誤值,不能求字符串長度 printf("%d\n",sizeof(buf)); |
注意:語法級別的越界 |
char p[3]=”abcde”; //編譯器不報錯,運行時錯誤(並不會崩潰),原因是越界了導致結尾沒有了\0,可能等在內存某處找到\0結果錯誤 printf("%d\n",strlen(p)); //不確定 printf("%d\n",sizeof(p)); //6
|
const int a = 10; int const b = 11;//兩者相同 //可看離const修飾符最近的變量/修飾符類型 const char* c = NULL;//const 在*號左邊,表示指向的內容不可寫 char* const d = NULL;//const 在*號右邊,表示指向不可變 const char* const e = NULL; 指針做函數參數時,傳入參數一般加上const,防止被改動 |
數組與字符串
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.