【问题标题】:Problem when assigning a pointer to an enum variable in C将指针分配给C中的枚举变量时出现问题
【发布时间】:2010-12-20 19:38:17
【问题描述】:

我收到“来自不兼容指针类型的赋值”的警告。我不明白为什么会发生此警告。除了整数之外,我不知道还有什么可以声明“the_go_status”变量。 (注意:这不是所有的代码,只是我贴出来的一个简化版本来说明问题。)

警告出现在我下面包含的示例的最后一行。

//In a header file  
enum error_type  
{  
    ERR_1 = 0,  
    ERR_2 = 1,  
    ERR_3 = 2,  
    ERR_4 = 4,  
};  


//In a header file  
struct error_struct  
{  
   int value;  
   enum error_type *status;  
};  



//In a C file  
int the_go_status;  

the_go_status = ERR_1;  

//Have the error_struct "status" point to the address of "the_go_status"  
error_struct.status = &the_go_status;    //WARNING HERE!

【问题讨论】:

    标签: c pointers enums warnings int


    【解决方案1】:

    因为status是一个指向枚举error_type的指针,而the_go_status是一个指向int的指针。它们是指向不同类型的指针。

    【讨论】:

    • 这是真的,但他想要做的似乎是,我不敢相信我终于把它看作是最好的形容词,非常臭。
    • codeySmurt:是的,你是对的。 &the_go_status 是一个指向 int 的指针。
    • 更具体地说,&the_go_status 是指针(如果已声明)指向的地址。
    • 所以,对于 int * 指针; pointer = &anotherPointer 你可以设置一个指向另一个指针地址的指针,从而指向那个值。
    【解决方案2】:

    我不确定这是否与您的警告完全相关,但要非常小心地将对局部变量的引用分配给结构内的指针。如果the_go_status 是本地的,那么只要您的函数返回,对该本地的引用就会失效。因此,如果您的代码(或其他人的代码)在声明 the_go_status 的函数之外使用您的 error_struct 实例,事情很快就会中断。

    【讨论】:

      【解决方案3】:

      这是因为enum error_type *int * 不兼容,因为它们指向不同类型(甚至可能是不同大小)的值。您应该将the_go_status 声明为:

      enum error_type the_go_status;
      

      虽然简单地转换指针(即(enum error_type *)&the_go_status)会使警告消失,但在某些平台上可能会导致错误。见Is the sizeof(enum) == sizeof(int), always?

      【讨论】:

        【解决方案4】:

        如果你想使用指针,你应该声明一个指针:

        int * the_go_status
        

        否则你声明一个原语,它不是放在堆上,而是放在栈上。 (请纠正我的错误)

        但是,我完全不明白您为什么要使用指针。只需在你的结构定义中做这样的事情:

        enum error_type status;
        

        并将最后一行更改为:

        error_struct.status = the_go_status; 
        

        【讨论】:

        • 仅仅声明一个指针没有任何好处,你必须将它指向某个东西。
        • 真的。至于任何其他类型的“变量”,您必须设置一次,因此它具有值。然而,由于这是编程最基本的事情之一,我认为这是显而易见的
        【解决方案5】:

        “the_go_status”应输入“enum error_type”。 你可以 typedef 枚举

        【讨论】:

          【解决方案6】:
          //This might be the simplest 
          
          #include<stdio.h>
          typedef enum {err_1=0,err_2=1,err_3=2,err_4=4}error; 
          typedef struct
          {
              int val;
              error* status;
          
          }errval;
          
          int main() {
          
              error the_go_status=err_1;  
              errval val1;//just a variable name for the struct
              val1.status=&the_go_status;
              printf("%d",val1.status);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-06-01
            • 2014-09-20
            • 1970-01-01
            • 1970-01-01
            • 2016-04-13
            • 1970-01-01
            • 1970-01-01
            • 2022-07-06
            相关资源
            最近更新 更多