【问题标题】:warning: passing argument 1 of ‘foo’ discards ‘const’ qualifier from pointer target type警告:传递“foo”的参数 1 会从指针目标类型中丢弃“const”限定符
【发布时间】:2016-04-30 09:06:19
【问题描述】:
#include<stdio.h>
void foo(int **p)
{
    int j=11;
    *p = &j;
    printf("%d ", **p);
}
int main(void)
{
    int i = 10;
    int *const p = &i;
    foo(&p);
    printf("%d ", *p);
    return 0;
}

编译时:

example.c:12:2: warning: passing argument 1 of ‘foo’ discards ‘const’ qualifier from pointer target type [enabled by default]
  foo(&p);
example.c:2:6: note: expected ‘int **’ but argument is of type ‘int * const*’
  void foo(int **p)

运行中:

11 11

这里的p是一个常量指针,为什么改变它的内容没有错误,只有警告?

我对上述程序的怀疑是因为以下程序:

#include<stdio.h>
int main(void)
{
    int var1 = 0, var2 = 0;
    int *const ptr = &var1;
    ptr = &var2;
    printf("%d\n", *ptr);
    return 0;
}

编译时:

error: assignment of read-only variable ‘ptr’
    ptr = &var2;

【问题讨论】:

  • post 可能会有所帮助

标签: c compiler-errors constants compiler-warnings


【解决方案1】:

int * const p; 表示 指向 int 的常量指针,其中 p 不能指向不同的位置。所以,你收到了警告。

【讨论】:

    【解决方案2】:

    为什么这里更改常量位置没有错误,只有 只是警告?

    案例1

    其实在:

    void foo(int **p) // p is a pointer to pointer to int
     {
        int j=11;
        *p = &j;  //equivalent of p = &i in main()
        printf("%d ", **p);
    }
    

    您不会更改 main 中 p 的值。你是吗?

    *p = &j;
    

    您只是更改了存储在 main() 的 p 中的值。

    案例2

    ptr = &var2; // You are making ptr point to the memory address of &var2
    

    这是非法的,因为 ptrconstant

    【讨论】:

      【解决方案3】:

      为什么更改内容没有错误,只有警告?

      在第一种情况下,您“仅”收到警告,因为您只是通过将const 传递到可能被滥用的上下文中,即被分配了一些东西,从而准备通往灾难的路线。然而,尚不清楚是否真的得到了分配。

      在第二种情况下,代码实际上做了它可能没有做的事情,即分配给const,因此编译器将其视为错误。

      【讨论】:

        【解决方案4】:

        int * const p 是一个指向int 的常量指针(p 的位置是只读的)

        foo的原型必须是

        void foo(int * const *p) --> 指向 int 的 const 指针(*p 的位置只读)

        *p = &j;
        
        error: assignment of read-only location ‘*p’
        

        但这是有效的:

        **p = j; --> 取消引用*p = 在main 中访问i

        您正在寻找:

        #include <stdio.h>
        
        void foo(int * const *p)
        {
            int j = 11;
        
            **p = j;
            printf("%d ", **p);
        }
        
        int main(void)
        {
            int i = 10;
            int * const p = &i;
        
            foo(&p);
            printf("%d ", *p);
            return 0;
        }
        

        输出:

        11 11
        

        同样

        int var1 = 0, var2 = 0;
        int *const ptr = &var1;
        ptr = &var2; <-- You can not change the location of ptr
        

        【讨论】:

          猜你喜欢
          • 2011-03-08
          • 1970-01-01
          • 2013-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-29
          • 2011-03-19
          相关资源
          最近更新 更多