Copying pointers.

Ok, Im not sure if Im going to explain myself properly but I will try mybest :P

My question is: Can you copy a pointer? I mean, not copying the data, but copying the pointer so that you save another pointer pointing at the data.

This might be a pretty inefficient way of doing what I want to do, so I guess I should explain that too :P

Im trying to make a sorting routine. But, I wanna make several sorting routines so that I can ask to sort the data in several ways( array of object pointers ).

This is my first attempt at making sorting routines and Im starting to understand the difficulty of it :P

So, what I wanna do is that for each sorting routine, I make a new array of class pointers and sort them by comparing the data I wanna sort.

Now, If I would say:

Class1* array1[MAX];
Class1* array2[MAX];

array2[1] = array1[1];

would I then say "copy array1[1] to array2[1]"
or would it just say:"array2[1] points to whatever array1[1] is pointing to", meaning that if I then change what array1[1] is pointing to, array2[1] will point to that too.
Hope Im not being too vague :P
Pointers are just addresses, so when you say Ptr2 = Ptr1 you're giving Ptr2 the address currently stored in Ptr1.
No different from typing int a = b
Hi omk!
Warnis is right, pointers store values just like any other variable, but they store a special value, the adress of an object.But you can still work with their value just like any other variable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;


int main()
{
  int n=0; // a variable
  int *ptr1= &n; // a pointer to that variable
  int *ptr2; // another pointer

  ptr2=ptr1; // make the second pointer have the value (the adress) to wich the first pointer points to

  cout<<"The adress of 'n' is :"<<ptr1<<endl;
  cout<<"Again, the adress of 'n' is :"<<ptr2; // this should be the same as the cout above


  return 0;

}
when you say array2[1] = array1[1];, it means 'the second pointer variable in array2 should point to the address stored in the second pointer variable of array1. (remember arrays start at 0).
If you want to copy array1 completely to array2, you'll need to copy each element one by one, of course using a loop structure.
So finally yes, you can copy a pointer into another pointer, because basically a pointer is a variable(memory location) holding a memory address. If a pointer is a variable, it means it can 'vary', so you can change it. Now const pointers are another deal!
Topic archived. No new replies allowed.