0

I am programming a C application with eclipse when happens a strange event.

I have a function to which I pass a pointer to struct, then inside of function, I allocate to this pointer other pointer of same type, a simple allocation like this

pointer = otherPointer;

Then, magically, my allocation is completely ignored by the program. I have refined with gdb and I see like the program pass for this line and the instruction is ignored.

there are some people with idea of causes of this paranormal event?

In the program there are similar functions with similar behavior and the allocation is done correctly.

Here is the funciton in question:

void uah_pcb_extract_queue_head (struct UAH_PCB * pPCB, struct UAH_PCB_Queue * pQueue)
{
  if (pQueue->head->next != NULL)
  {
    pPCB = pQueue->head;
    pQueue->head = pQueue->head->next;
  }
  else if (pQueue->head != NULL)
  {
    pPCB = pQueue->head;//this allocation
    pQueue->head = NULL;//in this line the value has not changed
    pQueue->tail = NULL;
  }
  else
  {
    pPCB = NULL;
  }
}
4

2 回答 2

3

The reason you don't even see the change in gdb is that your compiler has probably optimised the assignment out of your function, since pPCB is not used again in it, and not returned.

If you want the change to affect the world outside of your function, you will need to pass in a pointer to a pointer, and then change the value it points to:

void uah_pcb_extract_queue_head (struct UAH_PCB ** pPCB, struct UAH_PCB_Queue * pQueue){
  /* code... */
  *pPCB = pQueue->head;
  /* more code... */
}

alternatively, you could return the address and avoid dealing with pointers to pointers:

 struct UAH_PCB * uah_pcb_extract_queue_head (struct UAH_PCB_Queue * pQueue){
  /* code... */
  struct UAH_PCB * pPCB = pQueue->head;
  /* more code... */
  return pPCB;
}
于 2013-03-29T20:51:05.177 回答
0

If you wish to return a pointer as a parameter, then you must use ** syntax:

EXAMPLE:

struct mystruct {
  int x, y;
};

void
myfunc (struct mystruct **pp) {
  *pp = malloc (sizeof mystruct);
}

/* ... */

int main(){
  struct mystruct *mystruct_p = NULL;
  /* After this call, mystruct_p should no longer be NULL... */
  myfunc(&mystruct_p); 
  /* do some more stuff */
}

"pp", in this example, is shorthand for "a pointer to a pointer".

'Hope that helps!

于 2013-03-29T20:28:54.927 回答