开发者

How copy part of int array to another int array in C/C++?

please can you help me? How can I copy part of one int开发者_如何学Python array to another int array?

Example:

typedef struct part {
  int * array;
} PART;

int array[] = {1,2,3,4,5,6,7,8,9};
PART out[] = new PART[3];

for (int i = 0; i < 3; i++)
{
  memcpy((char *)array[i * 3], (char *)out[i].array, 3 * sizeof(int));
}

But this don't working... :(


Ok you have 3 problems.

  1. You are casting an int to a char* (char *)array[i * 3]

    What you really mean is (char *)&array[i * 3]. ie take the address of the i*3th element.

  2. you are trying to copy data from an uninitialised array.

    you should allocate memory to out[i].array.

  3. You appear to have your memcpy the wrong way round.

The following code will work better:

typedef struct part {
  int * array;
} PART;

int array[] = {1,2,3,4,5,6,7,8,9};
PART out[] = new PART[3];

for (int i = 0; i < 3; i++)
{
  out[i].array = new int[3];
  memcpy( (char *)out[i].array, (char *)&array[i * 3], 3 * sizeof(int));
}

Make sure you remember to delete[] the memory allocated to out[i].array ...


You need to allocate memory for * array before doing memcpy.

Something like this:

typedef struct part {
    int * array;
} PART;

int array[] = {1,2,3,4,5,6,7,8,9};
PART out[] = new PART[3];

for (int i = 0; i < 3; i++)
{
     out[i].array = malloc(9*sizeof(int));
     // will copy 9 array values into out[i].array
     memcpy(out[i].array, array, 9 * sizeof(int));
}


The struct part of this is kind of irrelevant. What you are trying to do can be accomplished this way:

int src[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int part[3][3];

for (int i = 0; i < 3; ++i)
{
    std::copy(src + (3 * i), src + (3 * (i + 1)), part[i]);
}

An even better solution can be done by using std::vector instead of C-style arrays:

std::vector<int> a(src, src + 9);
std::vector<std::vector<int> > b;

for (int i = 0; i < 3; ++i)
{
    std::vector<int> c(a.begin() + (3 * i), a.begin() + (3 * (i + 1)));
    b.push_back(c);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜