I have a function which contains for loop for printing pointer to array index and value
but my problem is that i cannot find on the internet how to print index by pointer to array
I have tried many options but it always output adress, value or crash...
double func(double*startValueOfArrayPointer,double*endValueOfArrayPointer){
double *pointerI;
for(pointerI=startValueOfArrayPointer 1;pointerI<=endValueOfArrayPointer;pointerI )
{
printf("\n %d value is %.2lf", ,*pointerI);
}
}
i want it to output smth like this:
1 value is 23.32
2 value is 34.65
3 value is 1.76
...
Thanks in advance
CodePudding user response:
The difference has type of ptrdiff_t
and the correct way of printing it is:
printf("\n %td value is %.2lf", pointerI - startValueOfArrayPointer ,*pointerI)
or if your implementation does not support %td
:
printf("\n %lld value is %.2lf", (long long)(pointerI - startValueOfArrayPointer) ,*pointerI)
CodePudding user response:
For starters your function returns nothing though its return type is not void
.
Also the length modifier 'l'
in the format string has no effect.
Bear in mind that in C indices start from 0. Nevertheless your function can look the following way.
void func( const double *first, const double *last )
{
for ( const double *current = first; current != last; current )
{
printf( "\n%tu value is %.2f", current - first 1, *current );
}
}
Pay attention to that the pointer last
shall not be in the range of outputted values. Otherwise it will be difficult to specify an empty range for an array. That is the range is specified like [first, last )
.
For example if you have an array like
double a[N];
and want to output all values of the array using the function then the function is called like
func( a, a N );