Can someone please explain to me how the pointers were used in the line w/ the red font. I do not understand where the pointer pertains to and why there is still a need for that. Also why is it that a "+" sign was used to combine two array variables? ie: *(mpg+ctr). Thanks in advanced guys.

void main()
{
	char choice;
	
	double miles[10] = {240.5, 300.0, 189.6, 310.6, 280.7, 216.9, 199.4, 160.3, 177.4, 192.3}; 

	double gallons[10] = {10.3, 15.6, 8.7,14,16.3,15.7, 14.9, 10.7, 8.3, 8.4};

	double mpg[10];

	int ctr;

	for(ctr=0;ctr<10;ctr++)

	{

		cout.setf(ios::fixed);
		cout.setf(ios::showpoint);
		cout.precision(2);
 

	
		cout<<"Miles /"<<" Gallons = Mpg: "<<endl;
		
		*(mpg+ctr) = *(miles+ctr) / *(gallons+ ctr);  
		
		cout<<miles[ctr]<<" / "<<gallons[ctr]<<" = "<<mpg[ctr]<<endl;
		cout<<endl;
		
	}
}

>>*(mpg+ctr) = *(miles+ctr) / *(gallons+ ctr);

That's the same thing as this: mpg[ctr] = miles[ctr] / gallons[ctr]; Personally I do not like or use the pointer arithmetic as shown in your code snippet, but its just a matter of personal taste. IMO using the index method I show is a lot more clear what is going on, and of course requires little thinking about it. Programmers should write for clarity, not cuteness or an attempt to impress others.

*(mpg+ctr) is basically the same as mpg[ctr] Tearing it apart:
mpg points to the array.
mpg+ctr points to the ctrth element in the array.
*(mpg+ctr) therefore is the value at the ctrth element

Ok Thats nice. I have read somewhere in my C book that if an array is used by just its name,i.e, mpg then it will return the address of its 0th element and hence :

mpg and *(mpg+i) will give you same values for a Loop.

But, there is also written in the book that i[mpg] will also return the same value.

Can you explain me that how i[mpg] can return the same value as mpg ?

[ Please See the attached Code of my book ]

Can you explain me that how i[mpg] can return the same value as mpg?

Your book already explains it. mgp[i] becomes *(mpg + i) , and because addition is commutative you can change the order of the operands without affecting the result. Thus, i[mpg] is to mpg[i] as *(i + mpg) is to *(mpg + i) . It's basic math. :)

commented: Thanks for resolving my confusion :) +0

Don't get hung up on the i[mgp] construct because its rarely, if ever, used in real life. In my 20+ years programming I've not seen it even once except in an academic text book.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.