memcpy elements of an array

Dear All,

I started trying to learn C++ about a week ago, so please bear with me here. I'm trying to build a function that will insert one element before another in an array but I keep getting "Segmentation Faults".

Here's my first effort:

1
2
3
4
5
6
void ins_b_b4_a(double *arr, int a, int b)
{
  double temp = arr[b];
  memcpy(arr + a + 1, arr + a, sizeof(double) * (b-a));
  arr[a] = temp;
}


I want element b inserted before element a, e.g. I want [3, 4, 5, 6, 7, 8] to become [3, 7, 4, 5, 6, 8] where b == 4 and a == 1. Can anyone tell me where I'm going wrong? Is it that my two blocks of memory aren't allowed to overlap initially or something like that?
It works fine for me. Could it be that your array is not long enough? If no, post the whole code.
Really? Could you show me the code that worked for you please? For me, the following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

void ins_b_b4_a(double *arr, int b, int a);
void swap(double *arr, int b, int a);
void print(double *arr, int n);

int main ()
{
  double arr[] = {4, 6, 3, 8, 9, 2, 7, 3, 5, 1};
  print(arr, 10);
  ins_b_b4_a(arr, 6, 3);
  print(arr, 10);
  cout << "\n";
  return 0;
}

void ins_b_b4_a(double *arr, int a, int b)
{
  double temp = arr[b];
  memcpy(arr + a + 1, arr + a, sizeof(double) * (b-a));
  arr[a] = temp;
}

void swap(double *arr, int b, int a)
{
  double temp = arr[a];
  arr[a] = arr[b];
  arr[b] = temp;
}

void print(double *arr, int n)
{
  cout << "\n" << arr[0];
  for (int i=1; i<n; i++) cout << ", " << arr[i];
}


gives me a segmentation fault
It's OK. I've seen why; I'm being an idiot and putting my args the wrong way round. Sorry
That said, I'm still getting strange results. So the following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

void ins_b_b4_a(double *arr, int b, int a);
void swap(double *arr, int b, int a);
void print(double *arr, int n);

int main ()
{
  double arr[] = {4, 6, 3, 8, 9, 2, 7, 3, 5, 1};
  print(arr, 10);
  ins_b_b4_a(arr, 6, 3);
  print(arr, 10);
  cout << "\n";
  return 0;
}

void ins_b_b4_a(double *arr, int b, int a)
{
  double temp = arr[b];
  memcpy(arr + a + 1, arr + a, sizeof(double) * (b-a));
  arr[a] = temp;
}

void swap(double *arr, int a, int b)
{
  double temp = arr[a];
  arr[a] = arr[b];
  arr[b] = temp;
}

void print(double *arr, int n)
{
  cout << "\n" << arr[0];
  for (int i=1; i<n; i++) cout << ", " << arr[i];
}


gives me output of:

4, 6, 3, 8, 9, 2, 7, 3, 5, 1
4, 6, 3, 7, 8, 8, 8, 3, 5, 1

Why is that please? That is, why the repeated 8s?
Ah, gotcha. It seems memmove is the function for me. This works as if a buffer is being used, which is what I want I think. Thanks for your help though
Topic archived. No new replies allowed.