使用C中的指针的const用法
我正在讨论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的值(至少不是通过指针(没有强制转换const))。
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 输入“help”或“?” 求助 cdecl>解释const char * someArray 将someArray声明为const char的指针 cdecl>解释char * const someArray 将someArray声明为char的const指针 cdecl>解释const char * const s2 将s2声明为const指向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; }
此实现仅更改函数内的dest
和src
。 使得指针(或两者)中的任何一个对strcpy()函数或调用代码都没有任何好处。