今天尝试使用const indentifier,发现const变量还是可以修改的,迷惑了..
下面是代码,在compare(const void *a, const void *b)函数中,我试图修改a指向的值:
#include <stdio.h>
#include <stdlib.h>
int values[] = {40, 10, 100, 90, 20, 25};
int compare (const void *a, const void*b)
{
*(int*)a=2;
/* Then the value that a points to will be changed! */
return ( *(int*)a - *(int*)b);
}
int main ()
{
int n;
qsort(values, 6, sizeof(int), compare);
for (n = 0; n < 6; n++)
printf("%d ", values[n]);
return 0;
}
然后我也尝试改变a本身的值:
#include <stdio.h>
#include <stdlib.h>
int values[] = {40, 10, 100, 90, 20, 25};
int compare (const void *a, const void*b)
{
a=b;
return ( *(int*)a - *(int*)b);
}
int main ()
{
int n;
qsort(values, 6, sizeof(int), compare);
for (n = 0; n < 6; n++)
printf("%d ", values[n]);
return 0;
}
然而,我发现它们都有效.. 如果它们仍然可以更改,谁能向我解释为什么我需要在比较的参数列表中使用 const?
最佳答案
它仅在这种情况下有效,因为您正在处理的指针最初不是常量。抛弃常量然后修改一个值是未定义的行为。 UB 意味着应用程序可以做任何事情,从成功到崩溃,让紫色的龙从你的鼻孔里飞出来。
关于c - 为什么我可以修改C中的const指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10456144/