Doubt about why to use pointer* &array

Hi I have a doubt with a program that I created to still learning c++.

In this program,after a lot of effort, I could do the thing that I wanted.
This thing was to work with a dynamic array but in a function that I made:
1
2
3
4

void crearCentroide(cCentroide* &array){
//...
}


So why have I to use this form of passing the array(cCentroide* &vector)? Otherwise, i hadn'n been able to modify the values of the original vector.
but I don't understand the theory behind this. Thanks a lot. And sorry for my bad english

PD: cCentroide is a class with this definition (i explain it, just in case):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "centroide.h"
cCentroide::cCentroide() {}
cCentroide::cCentroide(float a, float b) : x(a), y(b){}
void cCentroide::Establecer(float a, float b){x = a, y=b;}

void cCentroide::Leer(float &a, float &b){
    a = x;
    b = y;
}







You only need to do that if you're trying to modify the pointer itself, not the thing the pointer points to.
For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

int first[] = { 10, 20 };
int second[] = { -10, -20};

void display(int *array){
    std::cout << array[0] << ", " << array[1] << ", " << array << std::endl;
}

void modify_array(int *array){
    array[0] *= 2;
    array[1] *= 3;
}

void modify_pointer(int *&pointer){
    pointer = pointer == first ? second : first;
}

int main(){
    int *p = first;
    display(p);
    modify_array(p);
    display(p);
    modify_pointer(p);
    display(p);
    modify_array(p);
    display(p);
    modify_pointer(p);
    display(p);
    return 0;
}
The output will be
10, 20, 536246E
20, 60, 536246E
-10, -20, 9E9053A
-20, -60, 9E9053A
20, 60, 536246E
(Note: the hex values are merely for illustrative purposes.)
Last edited on
So, we can pass a pointer by value (with*) and by references (with * &) ?

And is it the same for an array? Or an array can't be passed by value?

That's right, an array can't be passed by value. You can only pass a pointer or a reference to an array.
Thanks a lot
Topic archived. No new replies allowed.