c - 为什么我可以修改C中的const指针?

标签 c memory pointers

今天尝试使用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/

相关文章:

在最大堆中分配字节 [] 时出现 Java OutOfMemoryError

c - 在 C 中传递数组指针并从不同数组中获取值

c 访问不同翻译单元中的数据成员

c - 在自己编写扩展之前要在 C 中实现多少 lisp?

c++ - 与计算着色器和 imageStore 的内存一致性

javascript - 如何防止javascript堆栈溢出?

c - 通用 HashMap,不需要的输出 (C)

c - 是否有任何工具可以为有效的 C 程序生成报告

c - sizeof 运算符的操作数

c - 如何读取c中的换行符