Alright, I think this should do you, but my C's a little rusty:
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
void swap_spec(int* a, int* b)
{
int tmp = NULL;
tmp = *a;
*a = *b;
*b = tmp;
}
int main()
{
vector<int> test(4);
test[0] = 5;
test[1] = 4;
test[2] = 3;
test[3] = 2;
swap_spec(&test[0], &test[1]);
printf("%d %d", test[0], test[1]);
return 0;
}
What I have done here is "swap the values at two memory locations", and then passed in the locations of the first and second element of your vector.
Let's go over your code, see if we can't clear some of what's going on up:
void swap_spec(vector<int>* a, vector<int>* b)
This says: Give me two pointers
to vectors storing ints
. When you're dealing with the elements of a vector, you just pass around the type stored in the vector: in this case, int
:
void swap_spec(int a, int b)
However, C/C++ are pass-by-value, which means the passed values would be copied, and then used locally - meaning, you could not effect the overal program environment by passing in the values.
You got this, which is why you passed in pointers.
Instead, you need to pass in pointers to the values
:
void swap_spec(int* a, int* b)
Technically, you're passing-by-value a memory address. Anyway - This lets you interact with memory (and this variables, objects, etc) outside of the function, in the overal program.
swap_spec(*test[0], *test[1]);
This passes in the values stored at the memory locations stored in test[0]
, which is invalid, because it's five.
What you want is:
swap_spec(&test[0], &test[1]);
Which pass in the memory addresses of those values, which is what you wanted.