字元陣列和strcyp函式

2021-07-27 07:24:51 字數 982 閱讀 7163

字元陣列:

1. 字元陣列後有乙個『\0』。

如:char str[10] = "123456789";

最多能放10-1 = 9 個字元。最後乙個存放字串的結束標識『\0』。

2.  在給字元陣列賦值時,別忘了手動加上乙個『\0』。

strcpy函式:

strcpy( char *s1,char *s2)他的工作原理是,掃瞄s2指向的記憶體,逐個字元付到s1所指向的記憶體,直到碰到'\0',

練習題:

1. 找錯

void test1()

void test2()

strcpy(string, str1);// i,i沒有宣告。

}void test3(char* str1)

}

2. 對下面的程式進行分析

void test2()

strcpy( string, str1 );

}

解答:如果面試者指出字元陣列str1不能在陣列內結束可以給3分;如果面試者指出strcpy(string, str1)呼叫使得從str1記憶體起複製到string記憶體起所複製的位元組數具有不確定性可以給7分,在此基礎上指出庫函式strcpy工作方式的給10分;

str1不能在陣列內結束:因為str1的儲存為:,沒有'\0'(字串結束符),所以不能結束

strcpy( char *s1,char *s2)他的工作原理是,掃瞄s2指向的記憶體,逐個字元付到s1所指向的記憶體,直到碰到'\0',因為str1結尾沒有'\0',所以具有不確定性,不知道他後面還會付什麼東東。

正確應如下

void test2()

str[i]='\0';//加上結束符

strcpy( string, str1 );

}

有關字元陣列和字串的函式

字串可以用字元陣列與字串變數兩種方式來儲存,效果類似。一 用字元陣列來儲存字串 char st1 100 st2 100 字元陣列說明 cin st1 st2 long a,b 輸入 hello,world 則st1 st2 字元 0 為字串結束標誌 1.字元陣列長度 strlen st1 如a s...

函式指標 函式指標陣列 字元指標陣列

資料型別 指標名字 引數列表 int function int int include include intadd int a,int b int sub int a,int b int mul int a,int b int div int a,int b int main int argc,c...

函式內返回字元陣列和字元指標的問題

1 include char arrstr char arr hello world return arr int main char str arrstr printf s str 2 include char arrstr char p hello world return p int main...