?最近在看C語言代碼時碰到了這個問題,結合查找的資料對這C的知識點做了一下小結,寫了一份測驗它們的代碼,test1函式穿了一個char* const的指標,如果對它增加,會報錯,它是只讀的,但是可以對指標所指位置的內容進行更改,test2函式測驗的是const char型別的引數,test3函式測驗的是char const 的引數,注釋部分是一些錯誤寫法和提示資訊,也就是一些反面教材,
#include <stdio.h>
//TEST1
void test1(char* const p){
// p++;
//compile error:
// increment of read-only parameter ‘p’
*(p+3) = 'D';
*(p+4) = 'E';
}
//TEST2
void test2(const char* p){
p++;
// *(p) = 'B';
//error:
// assignment of read-only location ‘*p’
p++;
printf("test2 func string:%s\n", p);
}
//TEST3
void test3(char const* p){
p++;
// *(p) = 'B';
//error:
// assignment of read-only location ‘*p’
printf("test3 func string:%s\n", p);
}
int main()
{
char str[27];
for(int i = 0;i < 26;i++ ) str[i] = 'a'+i;
str[26] = '\0';
printf("original string: %s\n", str);
test1(str);
printf("after test1 string: %s\n", str);
test2(str);
test3(str);
return 0;
}
?小結一下,const放在*的前面都是表示不能通過指標修改引數所指位置的內容,const放在*后面則是表示不能夠修改引數的值,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/501831.html
標籤:C++
