標籤:
一、文字常量地區
#include <stdio.h>int main(){char *p = "hello";int i = 0;for(i = 0;i<6;i++){printf("%c",*(p+i));}*p = '1';}
大家分析驗證以上代碼。p 是一個指標變數,儲存地址,“hello”是一個字串佔6個位元組,當我們用printf的時候可以輸出"hello",我們得出結論,p儲存的是存放‘h’的記憶體的地址,當我們*p = ‘1‘,去寫這塊記憶體的時候,會出現段錯誤。
依據以上現象,我們引出以下概念:
"hello"存放在 文字常量區,這個區用來存放代碼中出現的字串常量,而且這塊記憶體地區僅僅能讀不能寫,下面對程式記憶體做總結:
二、程式記憶體總結
程式執行起來後分為一下幾塊記憶體地區:
1、代碼區
存放各種語句產生的指令。
2、文字常量區
字串常量放在這裡。
比方 char *p = "hello";
3、棧區
局部變數,由系統自己主動申請釋放,生存周期為模組開始到模組結束。
4、堆區
malloc free,由程式猿自己申請釋放。
5、靜態儲存區
全域變數 static 變數放在這裡,程式開始申請出來。程式結束釋放。
三、結合代碼綜合分析
#include <stdio.h>char a[10] = "hello"; //“hello”字串儲存在全域數組中,在 靜態儲存區。int main(){char b[10] = "hello"; //“hello”儲存在數組b中,在棧區。char *p1 = "hello"; //“hello”儲存在文字常量區,p1儲存了存放‘h’的記憶體的地址,p1在棧區。char *p2 = NULL;//p2 在棧區*p = '1';//錯誤。這塊地區僅僅能讀。p2 = (char*)malloc(10);// 在堆中申請10個位元組的記憶體,並把這塊記憶體的地址存放在p2中。strcpy(p2,"hello");//把"hello"字串複製到堆記憶體中。free(p2);}
四、字串操作函數的基本原理
1、printf
原型 int printf(const char* p,...);
關於const與指標 參考 http://blog.csdn.net/xiaoliu0518/article/details/32943713
printf函數是一個可變參數函數,參數個數不定,第一個參數是const char* p ,p 存放字串的地址,通過這個字串的內容去解析後面的變數然後輸出對應的內容。
比方 printf("%c",...);
當字串為"%c"的時候,printf原型可簡單理解為 printf("%c",char c),列印字元。
在比方printf("%s",...)
當字串為"%s"的時候。printf的原型能夠簡單理解為 printf("%s",const char *p),在printf中會一個一個列印字元,簡單邏輯例如以下:
int printf("%s",const char *p){ while(*p != '\0') { putchar(*p); p++; }}
所以這裡知道為什麼,%s的時候。後面能夠傳char 數組、字串常量、char* str了吧。由於形參是const char *p。
char a[10] = "hello";
printf("%s","hello");
printf("%s",a);
2、strlen
strlen簡單邏輯例如以下。依舊是推斷‘\0‘結束
int strlen(const char *str){ int len = 0; while(*str != '\0') { len++; str++; } return len;}依據形參,能夠有下面調用
strlen(字串常量)
strlen(數組名)
strlen(char*指標)
3、strcpy
strcpy簡單邏輯例如以下,依舊是推斷‘\0‘結束
void strcpy(char *dest,const char* src){ while(*src != '\0') {*dest = *src;dest++; src++;}*dest = '\0';}
通過以上三個範例,簡單瞭解字串相關函數的操作原理,注意都是要推斷‘\0‘。假設沒有‘\0‘。則地址一直往後加,就會訪問到非法記憶體。
以上3個範例僅僅寫簡單邏輯,並沒有考慮安全性。嚴謹性。大家能夠自己實現下 strlen strcpy。
再考慮 例如以下:
char *p = "hello";char a[10] = "hello";printf("%s",p);strcpy(p,"bye");printf("%s",a);strcpy(a,"bye");哪些代碼有問題?
指標知識梳理5-字串與指標,程式記憶體總結