vimer linux kernel 爱好者

const指针常量的一点心得

2021-07-02

const int *p,定义一个指向常量的指针,怎么用呢?如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// 看一个可以修改指针变量的情况
int main0(){
    int a = 0;
    int *p = &a;
    *p = 10;
    printf("a = %d\n", a);
    printf("*p is %d\n", *p); // 很容易通过*p修改a的值,理所当然
}

int main(){
    main0();

    int b = 0;
    const int *p = &b; // 此时的p指向了一个类型的地址,但不可以通过*p的方式来修改a的值
    //*p = 20;   test.c:25:8: error: assignment of read-only location ‘*p’
    b = 20;
    printf("b is %d\n", *p); // b is 20.  此时的*p可读不可写

    // 另一个实验
    const int c = 100;
    int *p1;
    p1 = &c; // warning:  assignment discards ‘const’ qualifier from pointer target type
    *p1 = 0; // 消除这个warning,可以使用  p1 = (int *)&c;
    printf("c = %d\n", c);

}

看到没有,也就是在c中,可以有办法修改const修饰的常量。 我现在有一个代码:

static char *brd_type = "dvt";
...
const char *cbd_type = of_get_property(root, "carrier_board_type", NULL);
// 这里就会报warning: assignment discards ‘const’ qualifier from pointer
// 需要修改  static const char *brd_type = "dvt";

of_get_property的实现为:

static inline const void *of_get_property(const struct device_node *node,
				const char *name,
				int *lenp)
{
	return NULL;
}

Comments

Content