Function Using Pointers in an Array

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 1961 Views - Last Post: 01 April 2011 - 12:57 PM Rate Topic: -----

#1 CodeWomanSRQ1234  Icon User is offline

  • New D.I.C Head

Reputation: 17
  • View blog
  • Posts: 34
  • Joined: 08-August 09

Function Using Pointers in an Array

Posted 30 March 2011 - 08:57 AM

Here is what I am trying to do:
Write a function

void switchEnds(int *array, int size);

that is passed the address of the beginning of an array and the size of the array. The function swaps the values in the first and last entries of the array.

Here is the code to switch two integers:

void exchange(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}

Demonstrate the function with a driver program.


Here is my code so far, I am stuck.
#include<iostream>
#include<iomanip>
using namespace std;

// Function prototype
void switchEnds(int *, int *);

int main()
{
	// define array
	const int TEMPS = 5;
	int temp[TEMPS];

	temp[0] = 32;
	temp[1] = 36;
	temp[2] = 40;
	temp[3] = 45;
	temp[4] = 54;

	switchEnds(temp, TEMPS);
	cout << "Calling the switchEnds function:" << temp[TEMPS] << endl;

	system("Pause");
	return 0;
}

// Function switchEnds is to switch values in the first and last array entries
	void switchEnds(int *p, int *q)
	{
		int temp = *p;

		*p = *q;

		*q = temp;
	}



Is This A Good Question/Topic? 1
  • +

Replies To: Function Using Pointers in an Array

#2 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,740
  • Joined: 08-August 08

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 09:08 AM

Pointers are a pain. Why use them when you don't need to?
#include <iostream>
void switchEnds(int ar[], int array_size);

using namespace std;
int main () {	
	const int TEMPS = 5;
	int temp[TEMPS];
	
	temp[0] = 32;
	temp[1] = 36;
	temp[2] = 40;
	temp[3] = 45;
	temp[4] = 54;
	
	switchEnds(temp, TEMPS);
	cout << "Calling the switchEnds function: " << temp[0] << " " << temp[TEMPS-1] << endl;
	return 0;
}

void switchEnds(int ar[], int array_size)
{
	int temp = ar[0];
	ar[0] = ar[array_size-1];
	ar[array_size-1] = temp;
}


Was This Post Helpful? 1
  • +
  • -

#3 sk1v3r  Icon User is offline

  • D.I.C Addict

Reputation: 231
  • View blog
  • Posts: 668
  • Joined: 06-December 10

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 09:18 AM

While I agree with CTphpnwb, for future reference you should know what you are doing wrong.

You are passing a pointer to the entire array instead of just its first value as the first argument, and for the second you are passing the integer value of 5, which is not a memory address, nor does it point to the last element of the array like think
so you would need to call like this
switchEnds(&temp[0], &temp[TEMPS - 1]);


Was This Post Helpful? 1
  • +
  • -

#4 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2247
  • View blog
  • Posts: 9,237
  • Joined: 18-February 07

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 09:23 AM

void switchEnds(int *p, int *q); <-- your code
void switchEnds(int *array, int size); <-- what you are trying to do

pointers may be a pain but one really should learn how to think about them rather than avoid them all together (although much in C++ is concentrated on avoiding pointers nearly altogether).


lets take a closer looks at CTphpnwb code. When you dereference an element of an array using the index operator [] keep in mind this equivalence:

a[i] <==> *(a + i)

So making this swap we change CTphpnwb's code into:

void switchEnds(int *ar, int array_size) {
 	int temp = *(ar + 0);
 	*(ar + 0) = *(ar + array_size - 1);
 	*(ar + array_size - 1) = temp;
}


Pointers are a pain. Learn them while you can so you can avoid them later.
Was This Post Helpful? 1
  • +
  • -

#5 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,740
  • Joined: 08-August 08

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 09:47 AM

While it's true that passing an array forces it to decay to pointers anyway, I think it's easier to think about and easier to read if you avoid using pointers. And if you have C++, why go back to C at all?

Of course, I don't understand why anyone would willingly use char instead of C++ strings either, so I admit I'm biased.
;)
Was This Post Helpful? 1
  • +
  • -

#6 sk1v3r  Icon User is offline

  • D.I.C Addict

Reputation: 231
  • View blog
  • Posts: 668
  • Joined: 06-December 10

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 09:53 AM

I find char strings easier to use :)
and there are times when pointers are needed, so it is best to get used to them and understand them imo
:D
Was This Post Helpful? 1
  • +
  • -

#7 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 10:17 AM

Quote

I think it's easier to think about and easier to read if you avoid using pointers.

How is this? Are you saying by avoiding the pointer notation for the parameter, it becomes easier? I think it obscures that you have a pointer. It's much clearer to write foo(void * const arr, size_t sz, ...) .

Rather than running from pointers, understand them. They are not massively complicated, and dodging them like this only puts you in a worse position.

Quote

And if you have C++, why go back to C at all?


Because sometimes what C++ provides is not quite what is needed, and sometimes you need to worry about interoperability. If you push around std strings, the CRT and all code needs to operate exactly the same. Not so with POD types and structures.

Dodging the C subset of C++ is a good way to ensure you limit yourself to a subset of real world work. This isn't hard. This is not rocket science. There is some tediousness involved, but running from the topic helps no one.

Quote

Of course, I don't understand why anyone would willingly use char instead of C++ strings either


You need a byte buffer of size 1024 bytes. What's the most efficient way to have this? Not with a string. The problem is that there is no middle ground in standard C++. There is raw array, which is syntactically primitive and tedious. There is string, which is inappropriate. There is vector, which is unnecessary for fixed size data.

Now there is std array in C++0x, if you weren't using boost array. So that's a better suggestion.
Was This Post Helpful? 1
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 10:56 AM

I got an error when I tried to compile that. Didn't you?

t.cc: In function 'int main()':
t.cc:14: error: invalid conversion from 'int' to 'int*'
t.cc:14: error:   initializing argument 2 of 'void switchEnds(int*, int*)'



Here's the code I tried, with comments:

#include<iostream>
#include<iomanip>

using namespace std;

void switchEnds(int *, int *);

int main() {
	const int TEMPS = 5;
	int temp[TEMPS] = { 32, 36, 40, 45, 54 };

	// temp can be considered a pointer
	// however, TEMPS is clearly an int
	switchEnds(temp, TEMPS);
	
	cout << "Calling the switchEnds function:" << temp[TEMPS] << endl;
	return 0;
}

void switchEnds(int *p, int *q) {
	int temp = *p;
	*p = *q;
	*q = temp;
}



Ironically, the switchEnds looks just fine.

You could get it compile if you did this: switchEnds(temp, temp+TEMPS-1);.

Or, maybe more clearly: switchEnds(&temp[0], &temp[TEMPS-1]);.

Having a swap function is nice... And C programmers love their pointers. But, um, this is C++. Use pass by reference for less pain and a more C++y feel.

e.g.
void switchEnds(int &p, int &q) {
	int temp = p;
	p = q;
	q = temp;
}
// ...
switchEnds(temp[0], temp[TEMPS-1]);



Ah! Hidden pointers make newbie C++ programmers happy.

Now, your next line is bugger all: cout << "Calling the switchEnds function:" << temp[TEMPS] << endl; You don't have a value at temp[TEMPS]. This should crash horribly. Perhaps you want to print the entire array, swap, and print again?
Was This Post Helpful? 1
  • +
  • -

#9 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 2,338
  • Joined: 20-August 07

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 12:29 PM

View Postsk1v3r, on 30 March 2011 - 04:53 PM, said:

I find char strings easier to use :)
Do you actually do much string manipulation or I/O with string data using char arrays? What do you find easier to use about them? I'm honestly struggling to think of anything beyond the most trivial string operations which don't need you to jump through dozens of hoops to prevent buffer overflows, memory leaks, etc, where the C++ string equivalents are usually a couple of simple lines.


The only example I can think of is formatted data, which is arguably simpler with printf/sprintf than with the <iomanip> libraries, although then again, sprintf is notorious for buffer overflows, and actually isn't as simple to use in production code since you end up needing to write extra safety checks.
Was This Post Helpful? 1
  • +
  • -

#10 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 2,338
  • Joined: 20-August 07

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 12:39 PM

View PostOler1s, on 30 March 2011 - 05:17 PM, said:

Rather than running from pointers, understand them. They are not massively complicated, and dodging them like this only puts you in a worse position.
Not always :-) The alternative approach is to learn about pointers conceptually, by getting to grips with smart-pointers and iterators instead, which are at least exception-safe and give you an easier time when you screw up, but still teach you everything you need to know about indirection, boundaries, iteration, etc.

This is the way Accelerated C++ teaches pointers; in fact, Accelerated C++ has a wonderful definition of a pointer - it introduces them as "random-access iterators", which, if you understand what an iterator is, makes for a very elegant, accurate explanation which describes in a single hit both the purpose of a pointer, and how to use one :)
Was This Post Helpful? 1
  • +
  • -

#11 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,740
  • Joined: 08-August 08

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 01:53 PM

Honestly, I think using pointers is like driving a stick shift in an era of all-electric cars. It may make you feel more macho, but it really isn't doing as much for you as you think. Pointers are supposed to point to locations in memory but in modern operating systems that's just an illusion.

Computer scientists have spent the last 40 years developing layers of abstraction for a reason: abstraction is powerful. Unless I had a good reason not to, I'd use vectors instead of arrays, and skip the pointers.
#include <iostream>
#include <vector>
using namespace std;
void switchEnds(vector<int> &myvec);

int main ()
{
	vector<int>temp;
	temp.push_back(32);
	temp.push_back(36);
	temp.push_back(40);
	temp.push_back(45);
	temp.push_back(54);
	
	cout << "First: " << temp[0] << " Last: " << temp[temp.size()-1] << endl;
	switchEnds(temp);
	cout << "After calling the switchEnds function:\n";
	cout << "First: " << temp[0] << " Last: " << temp[temp.size()-1] << endl;

  return 0;
}

void switchEnds(vector<int> &myvec)
{
	int last_item = myvec.size() - 1;
	int temp = myvec[0];
	myvec[0] = myvec[last_item];
	myvec[last_item] = temp;
}

Is this potentially slower or could it use more RAM? Yes, potentially, but you'll likely never notice a difference and development can be faster and easier, meaning fewer bugs. If you've got an application that absolutely requires pointers for some specific advantage then fine, but for the other 99.99% of projects I just don't see a reason for using them.
Was This Post Helpful? 1
  • +
  • -

#12 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 02:33 PM

It's not a macho thing; it's a concept thing. In C++ you can avoid pointers to some extent, but they're always lurking there, under the facade, ready to surprise you. If you're going to do anything significant with C++, you need to understand pointers well, though if you may vow to avoid them like the plague.

Even with the STL, they're often just waiting to jump out at you. They can be a constant hassle or useful friend.

e.g.
void switchEnds(vector<int> &myvec) {
	int temp = *myvec.begin();
	*myvec.begin() = *myvec.rbegin();
	*myvec.rbegin() = temp;
}



C++ programmers, make friends with you pointers. Even if you choose to lock them in the basement and pretend they aren't there.

This post has been edited by baavgai: 30 March 2011 - 02:34 PM

Was This Post Helpful? 2
  • +
  • -

#13 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2834
  • View blog
  • Posts: 9,740
  • Joined: 08-August 08

Re: Function Using Pointers in an Array

Posted 30 March 2011 - 02:43 PM

View Postbaavgai, on 30 March 2011 - 05:33 PM, said:

C++ programmers, make friends with you pointers. Even if you choose to lock them in the basement and pretend they aren't there.

Well I guess that's what I'm saying: Understand them, but keep them locked in the basement where they belong. ;)
Was This Post Helpful? 1
  • +
  • -

#14 CodeWomanSRQ1234  Icon User is offline

  • New D.I.C Head

Reputation: 17
  • View blog
  • Posts: 34
  • Joined: 08-August 09

Re: Function Using Pointers in an Array

Posted 01 April 2011 - 07:23 AM

Thank you all so much! So much to learn, so little time. :rolleyes2:

Hmmm, looks like someone hacked DIC and added Charlie Sheen's pictures to ours in this link. Weird!
Was This Post Helpful? 1
  • +
  • -

#15 sk1v3r  Icon User is offline

  • D.I.C Addict

Reputation: 231
  • View blog
  • Posts: 668
  • Joined: 06-December 10

Re: Function Using Pointers in an Array

Posted 01 April 2011 - 09:02 AM

April fools ;)

This post has been edited by sk1v3r: 01 April 2011 - 09:03 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2