Passing an Array by Reference

I have written the following function to switch letters between two indexes in an array of characters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
char* switchAround(char* chars, int a, int b)
{
	if(a < 0 || b < 0)
		return chars;
	if(a < b)
	{
		char temp;
		temp = chars[b];
		chars[b] = chars[a];
		chars[a] = temp;
		return switchAround(chars, a + 1, b - 1);
	}
	return chars;
}


but when it gets to the line chars[b] = chars[a]; it throws the following exception:

Unhandled exception at 0x00fa19f0 in Recursion Project.exe: 0xC0000005: Access violation writing location 0x00fa7847.

I know I'm handling the pointer wrong somehow, but I don't understand the problem.
Last edited on
Looks fine to me. You must be calling the function incorrectly.

Either you're not giving it a valid buffer, or you're giving it a value for 'b' that's too high.

Indeed I was using the function incorrectly. I was passing it char* alphabet. I switched it to char[] alphabet and it works fine. But can someone help explain why these two are different? I found this article http://www.cplusplus.com/forum/articles/9/ but it leaves me just about as confused as when I started.
Because they do two different things.

An array creates memory:

  char p[ 4 ];

That creates a block of memory four bytes long. You can get the address of the beginning of the block of memory by using p directly, because the compiler will automatically convert it to a pointer for you. Hence, strlen( p ); works, passing the address of the first char in p[].

A pointer only accesses memory:

  char* q;

That creates a pointer to some block of memory, somewhere. Maybe.
Unlike before, where memory was allocated for your array, we now just have a place to keep an address. As of yet, it doesn't point anywhere meaningful. That's why you should initialize to NULL.

  char* q = NULL;

Now we know can check for sure that it doesn't point anywhere before trying to use it:

1
2
3
int len;
if (q) len = strlen( q );
else   len = 0;

Before you use it, you must make it reference memory that has been allocated for you. You can use the address of something that exists:

  q = p;

or you can create a new block of memory:

  q = new char[ 4 ];

(which you must later free with delete [] q;).

Hope this helps.
Topic archived. No new replies allowed.