help with pointer

rewrite loops without pointers or []

Page 1 of 1

3 Replies - 1499 Views - Last Post: 29 November 2009 - 05:42 PM Rate Topic: -----

#1 kyousuke805   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 27-November 09

help with pointer

Post icon  Posted 29 November 2009 - 05:08 PM

The directions to my problem are:

Rewrite the following function so that it returns the same result, but does not increment the variable ptr. Your new program must not use any square brackets, but must use an integer variable to visit each double in the array. You may eliminate any unneeded variable.

  double computeMean(const double* scores, int numScores)
	{
		const double* ptr = scores;
		double tot = 0;
		while (ptr != scores + numScores)
		{
			tot += *ptr;
			ptr++;
		}
		return tot/numScores;
	} 



When I looked at this I thought easy, I will just declare a new variable i and set it to ptr and increment i but that does not compile. The only way I know to traverse arrays are through the [] operators and through pointer, both of which I cannot use here. Can anyone help?

Is This A Good Question/Topic? 0
  • +

Replies To: help with pointer

#2 ccubed   User is offline

  • It's That Guy
  • member icon

Reputation: 165
  • View blog
  • Posts: 1,416
  • Joined: 13-June 08

Re: help with pointer

Posted 29 November 2009 - 05:10 PM

There's another method. It's called array pointer notation. It goes like this.

*(ptr+<pos>)
Was This Post Helpful? 0
  • +
  • -

#3 kyousuke805   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 27-November 09

Re: help with pointer

Posted 29 November 2009 - 05:14 PM

So in this case pos is how many steps you want to move? For example,
*(ptr+<pos>) is equal to (ptr + 1), assuming that pos = 1? But then wouldn't that be incrementing prt? I am not allowed to increment ptr..
Was This Post Helpful? 0
  • +
  • -

#4 ccubed   User is offline

  • It's That Guy
  • member icon

Reputation: 165
  • View blog
  • Posts: 1,416
  • Joined: 13-June 08

Re: help with pointer

Posted 29 November 2009 - 05:42 PM

View Postkyousuke805, on 29 Nov, 2009 - 04:14 PM, said:

So in this case pos is how many steps you want to move? For example,
*(ptr+<pos>) is equal to (ptr + 1), assuming that pos = 1? But then wouldn't that be incrementing prt? I am not allowed to increment ptr..


No, you're not changing ptr. * is derefence. In this case, it dereferences to the pos place in the array pointed to by ptr.

ie:

ptr+0 is position 0
ptr+1 is position 1

etc
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1