Pointer for array to calculate average in C++ -


i got question on pointer in c++ :

write function computes average value of array of floating-point data:

double average(double* a, int size)

in function, use pointer variable, not integer index, traverse array elements.

and here solution :

int main() { const int size = 5; double num_array[] = {2,2,3,4,5};  double* = num_array; cout << average(a,size); cout << endl;  system("pause"); return 0; }  double average(double* a,const int size) { double total = 0; (int count =0; count< size; count++){     total = total + *(a + count); } return total/size; } 

it works fine have question on loop on pointer in average function. if replace statement in loop :

    total = total + a*; 

(i thought supposed add number in array unfortunately gives me wrong answer)

so *(a + count) do? if possible, can please brief me on how works?

thanks in advance.

a pointer double.

if write *a, pointer gets dereferenced , data pointer points at, i.e. double value. note asterisk has in front of pointer. (it's "prefix" unary operator.)

a* no valid syntax (it tries multiply a still has follow ...)

a + count pointer arithmetic. gives a count numbers of elements offset original a pointer. points count-th element in array.

*(a + count) dereferences pointer, gives count-th element of array.

a[count] same; it's nicer syntax.

note: can use a++ in loop. increments pointer 1 position in array. next time dereference a using *a, returns next entry. loop can rewritten this:

double total = 0; (int count = 0; count < size; count++){     total = total + *a;    // access element points     a++;                   // move pointer 1 position forward } 

you can combine increment , dereferencing operations 1 expression. postfix-increment syntax a++ return old pointer , increment pointer 1 position. dereferencing a++ means dereference old pointer.

double total = 0; (int count = 0; count < size; count++){     total = total + *(a++); } 

the second note want give you don't need integer variable here count element. since pointer carries information, counter used stop loop. can done comparing pointer "end pointer", keep in variable:

double total = 0; double *end = + size; // store end of array while(a < end) {     total = total + *(a++); } 

as can see, converted for loop while loop since no longer need initialize or increment (remember: going next entry of array done in body!).

i hope illustrates pointer arithmetic little bit. can "calculate" pointers indexing variables (your count variable). can subtract them calculate offsets between pointers, example.


Comments

Popular posts from this blog

How to set a border for android Imageview in Longpress? -

java - Cast from Object to List<String>: CastClassException -

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -