相关疑难解决方法(0)

const指针结构的正确性

我有一个包含一些指针的结构.我希望这些价值不可修改.但是简单地编写const infront并不会使结构成员不可靠

typedef struct{
  int *x;
  int *y;
}point;

void get(const  point *p,int x, int y){
  p->x[0]=x;//<- this should not be allowed
  p->y[0]=y;//<- this should not be allowed
}
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向.

编辑:

因此,似乎没有简单的方法来使用函数原型来告诉属于该结构的所有内容都应该是不可修改的

c constants const-correctness

9
推荐指数
3
解决办法
1万
查看次数

有没有办法(实际上)保护对象不被修改?

const类型限定符使编译器的情况下发出一个错误消息试图修改声明为一个对象const,但这是不够的protection.For例如以下程序修改声明为所述阵列的两个元件const:

#include <stdio.h>

int main(void)
{
    const char buf[2] = { 'a','b' };
    const char *const ptr = buf;
    unsigned long addr = (unsigned long)ptr;

    *(char *)addr = 'c';
    addr = addr + 1;
    *(char *)addr = 'd';

    printf("%c\n", buf[0]);
    printf("%c\n", buf[1]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以,事实证明编译器没有足够的保护来保护对象不被修改.我们如何防止这种事情?

c

7
推荐指数
1
解决办法
159
查看次数

标签 统计

c ×2

const-correctness ×1

constants ×1