您的位置  > 互联网

TheC++(const)笔试题答案是众说纷纭

char * const cp; ( * 读成 pointer to ) 
cp is a const pointer to char 
const char * p; 
p is a pointer to const char; 
char const * p; 

同上,由于 C++ 中没有 const* 运算符,因此 const 只能属于前一种类型。

C++ 标准规定 const 关键字放在类型或变量名称之前。

const int n=5;    //same as below
int const m=10;
const int *p;    //same as below  const (int) * p
int const *q;    // (int) const *p
char ** p1; 
//    pointer to    pointer to    char 
const char **p2;
//    pointer to    pointer to const char 
char * const * p3;
//    pointer to const pointer to    char 
const char * const * p4;
//    pointer to const pointer to const char 
char ** const p5;
// const pointer to    pointer to    char 
const char ** const p6;
// const pointer to    pointer to const char 
char * const * const p7;
// const pointer to const pointer to    char 
const char * const * const p8;
// const pointer to const pointer to const char

说到这里,我们可以看看之前的笔试题:

const char *p="hello";       
foo(&p);  // 函数foo(const char **pp)下面说法正确的是[]

至于这个问题的答案,有很多意见。对于上面的问题,我们可以用以下程序来测试它:

#include 
#include 
#include 
void foo(const char **pp)
{
//    *pp=NULL;
//    *pp="Hello world!";
        *pp = (char *) malloc(10);
        snprintf(*pp, 10, "hi google!");
//       (*pp)[1] = 'x';
}
int
main()
{
    const char *p="hello";
    printf("before foo %s/n",p);
    foo(&p);
    printf("after foo %s/n",p);
    p[1] = 'x';
    return;
}

结论如下:

在 foo 函数中,您可以使 main 函数中的 p 指向新的字符串常量。在 foo 函数中,您可以将 main 函数中的 p 指向 NULL。在 foo 函数中,可以使 main 函数中的 p 指向它生成的内存块,并且可以在 main 函数中释放它,但会发出警告。但请注意,即使 p 指向 foo 中生成的内存块,它仍然不能与 p[1]='x' 一起使用;这样的语句会改变 p 所指向的内容。在 foo 中,不能使用 (*pp)[1]='x';这样的语句改变了 p 的内容。

因此,感觉 gcc 只是根据 const 的字面意思来限制它,也就是说,对于像 const char*p 这样的指针,无论 p 实际指向的内存还是常量的内存,都不能通过像 p[1]='x' 这样的语句来改变内容。但奇怪的是,在 foo 中,在指向 p 的内存后,你可以用这样的函数修改它的内容。