Hi all,

Just a simple question. How do i reverse a pointer to a set of values given that i know the size of the pointer?

int *temp = malloc(ptr_size);
// values of *ptr let say is 1......100,
// if i use the algorithm below, it gets me 1..50...1 and not 100...1

ptr_size2 = ptr_size;
temp = ptr;
for (i=0;i<ptr_size;i++) {

I also tried using temp[ptr_size] but still gives me the same result
Any idea?

Problem is you are going both ways!
You are incrementing i iterator and at same time decrementing ptr_size2.
Write something like:

ptr_size2 = ptr_size;
temp = ptr;
while (ptr_size2>=0) {

Thx for the quick response.
However after using ur codes, my compiler gave this warning:
operation on 'ptr_size2' may be undefined
and won't compile.

I only gave you an idea... Probably I messed up some interators, so in some point you call temp[negative]...
Check for this, it shouldn't be hard

Sorry, I still don't have any clue what is wrong. I also don't understand what is wrong with "incrementing i iterator and at same time decrementing ptr_size2"? Both are different integers, so incrementing iterator i won't affect ptr_size2 and vice versa.

I apologise, my bad (still early in the morning here :) )
I just realised that you decrease ptr_size2, not ptr_size, so it shouldn't be problem there.

This is likely what happens in my loop
temp[49] = ptr[51]
temp[50] = ptr[50]
temp[51] = ptr[49]

ptr[49] is actually referring to temp[49] since they are shared pointees. So it's almost the same like

temp[51] = temp[49]
temp[52] = temp[48]

Oh, yes... Your temp is actually same memory space as ptr. So:

temp[0] = ptr[99]

But ptr[0] is temp[0], which is actually ptr[99]

You have to make a REAL copy of ptr to temp, where: temp != ptr , but temp[i] == ptr[i]

Yes, i already tried that, as mentioned in my first post.
int temp[ptr_size];

temp = ptr;

It still gives me the same ptr result that is 1...50...1

yes sure that's what i did and got the result 1...50...1. It's weird and i'm sure i have checked my loops a couple of times. Perhaps any other alternatives?


int temp[ptr_size];
int ptr_size2 = ptr_size;

for (i=0;i<ptr_size;i++) {
temp[i] = ptr[ptr_size2--];

for (i=0;i<ptr_size;i++) {
ptr[i] = temp[i];

The second for loop is to get back a reversed ptr.

This article has been dead for over six months. Start a new discussion instead.