char const * const * const varName

时间:2015-12-09 09:12:58

标签: c pointers

我有一个具有以下签名的方法:

size_t advanceToNextRuleEntryRelatedIndex( size_t index, size_t nStrings, char const *const *const strings)

我如何解释这个:char const *const *const strings

谢谢, 帕。

3 个答案:

答案 0 :(得分:4)

char const *const *const strings
 ^    v    ^  v   ^  v
 |    |    |  |   |  |
 +-----    +--+   +--+

所以基本上它意味着所有指针和指针所指向的字符串都是常量,这意味着函数不能以任何方式修改传递的字符串(除非它被转换)。

e.g。

char* p{"string1","string2"};

将腐烂成char **

传递给

int n = 0; 
advanceToNextRuleEntryRelatedIndex( n, 2, p);

答案 1 :(得分:2)

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表示指向指针是不可变的,第一个表示指向的字符是不可变的。

答案 2 :(得分:1)

关键字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