[英]char const *const *const varName
我有一個方法具有以下簽名:
size_t advanceToNextRuleEntryRelatedIndex( size_t index, size_t nStrings, char const *const *const strings)
我怎么解釋這個: char const *const *const strings
?。
謝謝,帕萬。
char const *const *const strings
^ v ^ v ^ v
| | | | | |
+----- +--+ +--+
所以基本上它意味着所有指針和指針指向的字符串是常量,這意味着函數不能以任何方式修改傳遞的字符串(除非它被轉換)。
例如
char* p{"string1","string2"};
這將腐爛成char **
當傳遞給
int n = 0;
advanceToNextRuleEntryRelatedIndex( n, 2, p);
在char const *const *const strings
, strings
是指向char
指針的指針。 如果沒有const
限定符,它將如下所示:
char **strings;
const
限定符禁止在解除引用的特定級別修改解除引用的值:
**strings = (char) something1; // not allowed because of the first const
*strings = (char *) something2; // not allowed because of the second const
strings = (char **) something3; // not allowed because of the third const
換句話說,第三個const表示指針本身是不可變的,第二個const表示指向指針是不可變的,第一個表示指向的字符是不可變的。
關鍵字const使得此關鍵字之后的聲明變為常量。 代碼解釋比單詞更好:
/////// Test-code. Place anywhere in global space in C/C++ code, step with debugger
char a1[] = "test1";
char a2[] = "test2";
char *data[2] = {a1,a2};
// Nothing const, change letters in words, replace words, re-point to other block of words
char **string = &data[0];
// Can't change letters in words, but replace words, re-point to other block of words
const char **string1 = (const char **) &data[0];
// Can neither change letters in words, not replace words, but re-point to other block of words
const char * const* string2 = (const char * const*) &data[0];
// Can change nothing, however I don't understand the meaning of the 2nd const
const char const* const* const string3 = (const char const* const* const ) &data[0];
int foo()
{
// data in debugger is: {"test1","test2"}
**string = 'T'; //data is now {"Test1","test2"}
//1 **string1 = 'T'; //Compiler error: you cannot assign to a variable that is const (VS2008)
*string1=a2; //data is now {"test2","test2"}
//2 **string2='T'; //Compiler error: you cannot assign to a variable that is const (VS2008)
//3 *string2=a2; //Compiler error: you cannot assign to a variable that is const (VS2008)
string2=string1;
//4 **string3='T'; //Compiler error: you cannot assign to a variable that is const (VS2008)
//5 *string3=a2; //Compiler error: you cannot assign to a variable that is const (VS2008)
//6 string3=string1; //Compiler error: you cannot assign to a variable that is const (VS2008)
return 0;
}
static int dummy = foo();
/////// END OF Test-code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.