C語言學習(六)指標3 字串與指標
字串與指標
1.用字元指標指向一個字串
char* str = “Hello”;
C語言對字串常量是按字元陣列處理的,因此這裡實際上是把字串第一個元素的地址賦給str。
2.將a字串複製給b字串
方法1:
voidmain() {
charstr1[] = "hello world!";
charstr2[20];
inti;
for(i= 0; *(str1+i) != '\0'; i++) {
*(str2+i)= *(str1+i);
}
*(str2+i)= '\0';
printf("%s\n",str1);
printf("%s\n",str2);
}
方法2:用指標變數來處理
voidmain() {
charstr1[] = "hello world";
charstr2[20];
char*p1,*p2;
/*將兩個字串的首地址賦值給兩個指標變數*/
p1= str1; p2 = str2;
for(;*p1 != '\0'; p1++,p2++) {
*p2= *p1;
}
*p2= '\0';
printf("%s\n",str1);
printf("%s\n",str2);
}
3.字元指標作函式引數
將一個字串從一個函式傳遞到另一個函式,可以用地址傳遞的方法,即用字元陣列名作引數,也可以用指向字元的指標變數作引數。在被調函式中可以改變字串的內容,主調函式中得到被改變的字串。
例如:用函式呼叫實現字串的複製
方式1:用字元陣列作引數
voidmain() {
voidcopy(char str1[],char str2[]);
charstr1[] = "hello";
charstr2[] = "hello world";
printf("beforecopy str1 = %s , str2 = %s \n",str1,str2);
copy(str1,str2);
printf("aftercopy str1 = %s , str2 = %s \n",str1,str2);
}
voidcopy(char str1[],char str2[]) {
inti = 0;
while(str1[i]!= '\0') {
str2[i]= str1[i];
i++;
}
str2[i]= '\0';
}
輸出:
beforestr1 = hello,str2 = hello world
afterstr1 = hello,str2 = hello
方式2:用指標變數作引數
voidmain() {
voidcopy(char * str1,char * str2);
charstr1[] = "hello";
charstr2[] = "hello world";
char* s1,* s2;
s1= str1;
s2= str2;
printf("beforecopy str1 = %s , str2 = %s \n",str1,str2);
copy(s1,s2);
printf("aftercopy str1 = %s , str2 = %s \n",str1,str2);
}
voidcopy(char * str1,char * str2) {
while(*str1 != '\0') {
*str2 = * str1;
str2++;
str1++;
}
*str2 = '\0';
}
輸出:
beforestr1 = hello,str2 = hello world
afterstr1 = hello,str2 = hello
4.雖然用字元陣列和字元指標變數都能實現字串的儲存和運算,但它們是有區別的:
a)字元陣列由若干元素組成,每個元素中存放一個字元;字元指標變數中存放的是地址。
b)賦值方式。字元陣列只能對各個字元賦值,不能用以下辦法對字元陣列賦值:
charstr[14];
str= “hello”;
而對字元指標變數,可以採用下面的方式賦值:
char* a;
a= “hello”;
注意賦給a的是字串首元素的地址。