It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
这里的重点是代码int header = (((int)(txUserPtr) - 4)) UserTypes和struct指针转换的说明很有帮助!我应该如何设置传入指针txUserPtr,以使Fun()跳过以下几行。我不想执行error()

typedef union UserTypes
{
    SAUser           AUser;
    BUser            BUser;
    SCUser           CUser;
    SDUser           DUser;
} UserTypes;

typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;
typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;

typedef struct BUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } BUser;

typedef struct CUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } CUser;

typedef struct DUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } DUser;

//this is the function I want to test

void Fun(UserTypes * txUserPtr)
{

   int header = (*((int*)(txUserPtr) - 4));

   //the problem is here
   //how should i set incoming pointer "txUserPtr" so that
   //Fun() would skip following lines.
   // I don't want to execute error()

        if((header & 0xFF000000) != (int)0xAA000000)
        {
            error("sth error\n");
        }
   /*the following is the rest */
}

最佳答案

该代码依赖于未定义的行为以及各种实现定义的行为。在代码中的某处应该有一个结构类似于

typedef struct
{
  unsigned int header;
  UserTypes user;
} AHeaderPlusUserTypes;


找到该结构后,修复代码:

void Fun (AHeaderPlusUserTypes* txUserPtr)
{
  if((txUserPtr->header & 0xFF000000u) != 0xAA000000u)
  {
    error("sth error\n");
  }
  /*the following is the rest */
}

关于c - struct指针转换及其内存分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10832993/

10-11 22:58
查看更多