开发者

Assigning part of 2d array to a 1d array

How do I do the following:

int A[2][2];
int B[2];
A[1][0]=2;
B=A[1];
printf("%d",B[0])开发者_如何学Python; //prints out 2

must I use malloc? I know that in higher level languages the above method works, but I'm a little confused about what to do in C


You cannot assign to arrays (though you can initialize them, which is very different).

You can do what you want, by assigning to B element-by-element

B[0] = A[1][0];
B[1] = A[1][1];

or, with a loop

for (k=0; k<2; k++) B[k] = A[1][k];


The problem here is that the variable is declared as int B, when you should declare it as int B[2].

In your code, when you assign A[1] to B, it assigns the value of the first element of A[1] to B

You can declare as int *B, so you will assign the ptr of A[1] to B. As it is, depending on the compiler will not compile. To test, do:

int *B;
B = A[1];
printf("%d, %d", B[0], B[1]);


You could you memcpy().

#include <stdio.h>
#include <string.h>

int main() {
  int a[2][2] = {{1, 2}, {3, 4}};
  int b[2];

  // Syntax: memcpy(to, from, number_of_bytes_to_copy);
  // (to and from should be pointers)
  memcpy(b, a[1], sizeof(int) * 2);

  printf("%d %d", b[0], b[1]);
}

Output:

3 4


Arrays are not assignable. You cannot assign the entire array. Whether it's 2D, 1D or 42D makes no difference here at all.

Use memcpy

static_assert(sizeof B == sizeof A[1]);
memcpy(B, A[1], sizeof B);

write your own array-copying function or use a macro

#define ARR_COPY(d, s, n) do{\
    size_t i_, n_; for (i_ = 0, n_ = (n); i_ < n_; ++i_) (d)[i_] = (s)[i_];\
  }while(0)

ARR_COPY(B, A[1], 2);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜