繁体   English   中英

使用C中的指针的const用法

[英]const usage with pointers in C

我正在讨论C并且有一个关于使用指针的const用法的问题。 我理解以下代码:

const char *someArray

这是定义指向char类型的指针, const修饰符意味着不能更改someArray存储的值。 但是,以下是什么意思?

char * const array

这是另一种指定参数的替代方法,该参数是指向名为“array”的数组的char指针,该数组是const且无法修改吗?

最后,这个组合意味着什么:

const char * const s2

作为参考,这些来自第7章中的Deitel C编程书,所有这些都用作传递给函数的参数。

正如你所说的, const char*是一个指向char的指针,你不能改变char的值(至少不通过指针(不抛出constness))。

char* const是指向char的指针,您可以在其中更改char,但不能使指针指向不同的char。

const char* const是一个指向常量char的常量指针,即你既不能改变指针指向的位置也不能改变指针的值。

const int *,const int * const,int const *之间的区别是什么

向后读它......

 int* - pointer to int int const * - pointer to const int int * const - const pointer to int int const * const - const pointer to const int 
//pointer to a const
void f1()
{
    int i = 100;
    const int* pi = &i;
    //*pi = 200; <- won't compile
    pi++;
}

//const pointer
void f2()
{
    int i = 100;
    int* const pi = &i;
    *pi = 200;
    //pi++; <- won't compile
}

//const pointer to a const
void f3()
{
    int i = 100;
    const int* const pi = &i;
    //*pi = 200; <- won't compile
    //pi++; <- won't compile

}

你应该试试cdecl

~ $ cdecl
Type `help' or `?' for help
cdecl> explain 
declare someArray as pointer to const char
cdecl> explain 
declare someArray as const pointer to char
cdecl> explain 
declare s2 as const pointer to const char
cdecl>
char * const array;

这意味着指针是常量。 也,

const * const char array;

表示常量内存的常量指针。

重复其他用户写的内容,但我想提供上下文。

采取以下两个定义:

void f1(char *ptr) {
    /* f1 can change the contents of the array named ptr;
     * and it can change what ptr points to */
}
void f2(char * const ptr) {
    /* f2 can change the contents of the array named ptr;
     * but it cannot change what ptr points to */
}

使指针本身为const ,就像在f2示例中一样, 绝对是毫无意义的。 传递给函数的每个参数都按值传递。 如果函数更改了该值,它只会更改其本地副本,并且不会影响调用代码。

/* ... calling code ... */
f1(buf);
f2(buf);

在任何一种情况下,函数调用后buf都保持不变。


考虑strcpy()函数

char *strcpy(char *dest, const char *src);

一种可能的实现是

char *strcpy(char *dest, const char *src) {
    char *bk = dest;
    while (*src != '\0') {
        *dest++ = *src++;
    }
    *dest = *src;
    return bk;
}

此实现仅更改函数内的destsrc 使无论是三分球(或两者)的const将一无所获的的strcpy()函数或调用代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM