我与C中的strcmp
功能的工作,然后我看到的功能参数获得:将非常量字符数组传递为const char数组是可能的吗?
strcmp(_const char *s1, const char *s2)_;
而实际上我通过正常的字符数组,它的工作。任何想法为什么发生这种情况
我与C中的strcmp
功能的工作,然后我看到的功能参数获得:将非常量字符数组传递为const char数组是可能的吗?
strcmp(_const char *s1, const char *s2)_;
而实际上我通过正常的字符数组,它的工作。任何想法为什么发生这种情况
有两种使用const
关键字的指针方式有两种:
int my_int = 3;
const int* pt = &my_int; //prevent to modify the value that pointer pt points to
int* const ps = &my_int; //prevent to modify the value of pointer ps:
//it means the pointer is a const pointer, you can't modify the value of the pointer
//The value of the pointer ps is a memory address, so you can't change the memory address
//It means you can't reallocate the pointer(point the pointer to another variable)
int new_int = 5;
*pt = &new_int; //valid
*pt = 10; //invalid
*ps = &new_int; //invalid
*ps = 10; //valid
在strcmp
功能,这两个参数是指针指向一个常量的值,这意味着当你传递两个字符数组或字符指针到strcmp
函数,该函数可以使用这两个指针指向的值,但该函数无法修改您传递给它的值。这就是它工作的原因。
const
参考以类似的方式工作。
这工作,因为传递非常量代替常量是允许的。这是周围的其他方式被禁止:
char *hello = new char[20];
char *world= new char[20];
strcpy(hello, "hello");
strcpy(world, "world");
if (!strcmp(hello, world)) {
...
}
在声明中const
是为了告诉大家,功能将不修改字符串的内容的API的用户。在C++中,这很重要,因为字符串文字是const
。如果没有API的const
,这个调用将被禁止:
if (!strcmp(someString, "expected")) { // <<== This would not compile without const
...
}
如果您有例如下面的代码
char c = 'A';
char *p = &c;
const char *cp = &c;
那么就意味着你可以使用指针p
但你改变变量c
使用指针cp
例如可以不改变它
*p = 'B'; // valid assignment
*cp = 'B'; // compilation error
因此函数声明
int strcmp(const char *s1, const char *s2);
意味着该函数内的字符串S1所指出和s2不会改变。
我想你打算问一下变量如何比较数组的机制。 如果是这样的话,
经本实施例被宣布该指针存储该阵列的第一个元素和
字符串的结束点可以由检测空字符这又是被确定的初始地址数组的结束地址。这样说strcmp在调用指针指向字符串或传递的字符时,该命令将假定如下strcmp(“string1”,“string2”); ,因此比较照常进行。
嗯我猜这个和其他例子张贴在你身边可以得到一个更好的图片为您的答案。
非常感谢。这正是我所期待的。 – FrozenFrog 2014-08-29 18:45:26
我很高兴我可以帮助:) – 2014-08-29 18:48:25
星号不应出现在'* pt =&new_int;'和'* ps =&new_int;' – TisteAndii 2016-04-15 00:10:49