为什么要在C中修改const指针? [英] Why can I modify the const pointer in C?

查看:92
本文介绍了为什么要在C中修改const指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我尝试使用const标识符,但是我发现const变量仍然可以修改,这使我感到困惑.

Today I tried to use const indentifier, but I find the const variable can still be modified, which confuses me..

下面是代码,在compare(const void * a,const void * b)函数中,我试图修改 a 指向的值:

Following is the code, in compare(const void *a, const void *b) function, I tried to modify the value that a is pointing to:

#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 本身的值:

Then I also tried to change the value of a itself:

#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;
}

但是,我发现它们两者都可以工作. 谁能向我解释为什么如果仍然可以更改它们,为什么需要在compare参数列表中使用const?

However, I found both of them works.. Can anyone explain to me why I need to use const in the parameter list of compare if they can still be changed?

推荐答案

案例1:您正在使用静态强制类型转换来消除常量性.您违反了为该方法定义的合同.

Case 1: You are using a static cast to cast away the constness. You are violating the contract that was defined for the method.

情况2:您没有更改a(它是const)的内容,而是分配了一个包含const空指针的变量a.

Case 2: You are not changing the contents of a (which is const), but assigning the variable a which contains a const void pointer.

实际意义:在案例1.)中,如果a并非真正指向变量,您可以将自己开枪射击.

For practical implications: With case 1.) you could shoot yourself in the foot, in case a was not really pointing to a variable.

建议:仅当您知道自己在做什么时,才丢弃常数.

Suggestion: Cast away constness only if you know what you are doing.

这篇关于为什么要在C中修改const指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆