passing pointers and arrays

Jun 5, 2013 at 1:58pm
im having troubles with passing arrays and pointers. Im still not exactly sure on how i would pass a point that is an array to a function. not sure if i fdong this correctly!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void math ( double *model[]){  // * model picks up the numbers at that address?
 
for (x = 0 ; x<5; x++){

 *model[x] = 1.23453+x;
}

return (0);
}

int main (){

double pmodel;
pmodel = new double [10] ; // so this is the max the dynamic array can be??
math(&pmodel) // sned the address of the array?

// will pmodel now contain the correct values??

return (0);
}
Jun 5, 2013 at 2:22pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void math(double* model)
{
    for (x = 0; x<5; ++x)
        model[x] = 1.23453+x;
}

int main ()
{
double* pmodel = new double [5]; //You are using only 5 values in math function
math(pmodel) //pass pointer to a function

for (int i = 0; i < 5; ++i)
    std::cout << pmodel[i] << ' ';
}
Jun 5, 2013 at 2:51pm
The name of an array is also a pointer to the first element of the array. You can use this pointer to pass the array into functions, or to access the array in any other way you need. Thus, you only need:

void math(double* model)

as shown in MiiNiPaa's code.

However, when you pass the array (i.e. the pointer) into the function, there is no way for the function to know the size of the array. It is customary, therefore, for a function that takes an array in the form of a pointer, to also take the size of the array as a separate parameter:

1
2
3
4
5
void math(double* model, unsigned int modelSize)
{
    for (x = 0; x<modelSize; ++x)
        model[x] = 1.23453+x;
}


This allows the function to handle arrays of any size, without making assumptions about what that size will be.

EDIT: Of course, most people will tell you that the very best thing you can do is to learn how to use vectors as soon as possible, and use them instead of arrays wherever possible. Those people are 100% correct.
Last edited on Jun 5, 2013 at 2:52pm
Topic archived. No new replies allowed.