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?

Eg
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++) {
temp=ptr[ptr_size2--];
}

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

where you set the "ptr_size" value. Meybe it is equal to 50 ;)

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) {
temp[ptr_size-ptr_size2]=ptr[ptr_size2--];
}

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]
...
temp[99]=ptr[0]

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;
ptr=temp[ptr_size2--];

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

You have to do it for EACH i.
So put it in for loop

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?

Please post entire code, because your code should work then.

here:

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.