-1

Hello I have this problem. I made this function:

void* deque2array(tDeque * D){

    void *arr = NULL;

    int i;
    tNodo * aux = D->ppio;

    for(i=0; i < D->cant; i++){
        arr = aux->elem;
        arr++;
        aux=aux->sig;
    }

    return arr;
}

Then I made a tester to be sure that this function works right.

tDeque * queue = createDeque();

int x=5;
int y=2;
int z=3;

insertInDeque(queue, &x);
insertInDeque(queue, &y);
insertInDeque(queue, &z);

int* pointer = deque2array(queue);
int i;

for(i=0; i<numberOfElements(queue); i++){
    pointer = pointer + i;
    printf(" %d ", *pointer);
}

But all I get is memory address and I don't know what I am doing wrong.

Joseph
  • 45
  • 6

1 Answers1

1

You are doing several things wrong. First, you are posting an incomplete code example. We don't know what D->ppio, D->cant, aux->sig, or aux->elem are, nor do we know whether you are setting them properly in insertInDeque.

In deque2array:

arr = aux->elem

You probably want:

*arr = aux->elem

Otherwise, the function is returning the value stored in the last aux->elem + 1. It's hard to fathom how that will run without an exception if it's supposed to return a void*.

In your tester:

pointer = pointer + i

You are modifying pointer on every iteration of the loop. Thus pointer on the Nth iteration of the loop is the original value of pointer plus the sum of integers 0 to N, not the original value of pointer plus i as it appears it was intended. Again, it is a miracle if this code runs without an exception, since it will be reading memory beyond the bounds of the array. Given a large enough return value of numberOfElements(queue), this is guaranteed to produce an error.

Once you've fixed these problems, if I assume aux->elem is what I think it is, and insertInDeque does what I think it does, your new problem will be that you are inserting the addresses of x, y, and z into the structure, not the values, so it would then make sense for your corrected test code to print the addresses of the variables. As of now, since you are reading undefined memory locations, the results are not going to make sense regardless of what is actually in the data structure.

sqykly
  • 1,586
  • 10
  • 16