Reversing a character array

I am trying to create a function that will reverse the characters in a character array of any size/characters. I've done as much as I can but I am really stuck now. Shown below is just sample values for the size and elements, it has to be of any length/characters, I just find it easier to write when i'm using sample values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
	char arr[4] = {'a','b','c','d'};
	int SIZE = 4;
	for (int i = 0;i<SIZE/2; i++){
		for (int j= SIZE-1; j>=SIZE/2; j--){
			int c=arr[i];
			arr[i]=arr[j];
			arr [j]=arr[c];
		}
	}
	return 0;
}

I would recommend writing a method to do the reversing for you, then calling that method inside of your main function. An example of a reverse method would be.
1
2
3
4
5
6
7
8
9
10
void reverser(char* string, int length)
{
	int i;
	for (i = 0; i < length / 2; i++)
	{
		string[length - 1 - i] ^= string[i];
		string[i] ^= string[length - 1 - i];
		string[length - 1 - i] ^= string[i];
	}
}
Oh ok. I am still a little lost on how to get it to work though. I think I may have an extra loop. It's also telling me that i am calling the function wrong (expected '(' for function-style cast or type construction)
This is what i have so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void reverser(char arr[], int SIZE);
int main(){
		char arr[4] = {'a','b','c','d'};
		int SIZE = 4;
			for (int i = 0;i<SIZE/2; i++){
				reverser (char arr[], int SIZE);
			}
			return 0;
		}

void reverser(char arr[], int SIZE)
{
	int i;
	for (i = 0; i < SIZE / 2; i++)
	{
		arr[SIZE - 1 - i] ^= arr[i];
		arr[i] ^= arr[SIZE - 1 - i];
		arr[SIZE - 1 - i] ^= arr[i];
	}
}
You will need to look up how to make a pointer, this will give you a reference to the end of the file. Then you will need to determine the length of the string with that pointer reference. Then call your reverse function. If you are not held to using pointers another device could be useful with the link below.

http://www.cplusplus.com/reference/algorithm/reverse/
You only need one loop that runs from 0 to size/2. At each step, you want to swap an item in the first half with an item in the second half. To figure out the math, write out a few by hand. If the string has size characters then:
swap str[0] with str[size-1]
swap str[1] with str[size-2]
swap str[2] with str[size-3]
...
Topic archived. No new replies allowed.