Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

c - How to modify a output pointer for debug purpose?

I have a function like:

   typedef struct
   {
      bool    x; 
      bool    y; 
      bool    z;  
   } myStruct;

static void myFunction(const myStruct     *pTomystruct_out)
{
    if (pTomystruct_out->x == TRUE)
    {
        /*Do Something*/
    }
}

Now for some debug purpose I want to add debug code to set the pointer parameter always to TRUE. Within the function before the if statement I want to do something like:

pTomystruct_out.x = TRUE  /*This is not the correct way*/

How to do this in the right way?

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

pTomystruct_out is a pointer, so you have to dereference that for manipulating what is pointed. You can use * opetator to dereference:

(*pTomystruct_out).x = TRUE;

Also you can use -> operator where A->B means (*A).B:

pTomystruct_out->x = TRUE;

Also, this is not enough because the pointer pTomystruct_out is marked as const. You can use a cast to non-const pointer for having it allow modifications.

((myStruct*)pTomystruct_out)->x = TRUE;

This is syntactically collect, but it may be dangerous to modify the object that is thought not to be modified. Creating a copy of the object and modifying the copy is safer.

   typedef struct
   {
      bool    x; 
      bool    y; 
      bool    z;  
   } myStruct;

#if 1 /* debug mode */
static void myFunction(const myStruct     *pTomystruct_out_arg) /* change argument name */
{
    myStruct pTomystruct_debug_temp = *pTomystruct_out_arg; /* make a copy */
    myStruct *pTomystruct_out = &pTomystruct_debug_temp; /* declare a variable with original argument name */
    pTomystruct_out->x = TRUE; /* modify the copy */
#else
static void myFunction(const myStruct     *pTomystruct_out)
{
#endif
    if (pTomystruct_out->x == TRUE)
    {
        /*Do Something*/
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...