LoginSignup
2
1

More than 5 years have passed since last update.

配列を連結してあたらしい配列を返す

Posted at

いろいろな書き方、流儀があるけれど、初学者が書くのが concat1
ポインター使えるようになりました! STL 読んだことあります! ってのが書くのが concat2
ちゃんと C を書けるようになったら concat3 にたどり着く。

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

static inline int* concat1(const int *a, size_t alen, const int *b, size_t blen) {
  int *const p = malloc(sizeof(int) * (alen + blen));
  int i, j;
  i = 0;
  for (j = 0; j < alen; ++j, ++i) {
    p[i] = a[j];
  }
  for (j = 0; j < blen; ++j, ++i) {
    p[i] = b[j];
  }
  return p;
}

static inline int* concat2(const int *a, size_t alen, const int *b, size_t blen) {
  int *const p = malloc(sizeof(int) * (alen + blen));
  int *it;
  for (it = p; it != p + alen; ++it) {
    *it = a[it - p];
  }
  for (/* it = p + alen */; it != p + alen + blen; ++it) {
    *it = b[it - (p + alen)];
  }
  return p;
}

static inline int* concat3(const int *a, size_t alen, const int *b, size_t blen) {
  int *const p = malloc(sizeof(int) * (alen + blen));
  memcpy(p, a, sizeof(int) * alen);
  memcpy(p + alen, b, sizeof(int) * blen);
  return p;
}

#define LENGTH(array) sizeof(array)/sizeof(*array)

static inline void dump(const int *array, size_t size) {
  const int *const end = array + size;
  while (array != end) {
    printf("%d ", *array++);
  }
}

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

  int *const p1 = concat1(a, LENGTH(a), b, LENGTH(b));
  int *const p2 = concat2(a, LENGTH(a), b, LENGTH(b));
  int *const p3 = concat3(a, LENGTH(a), b, LENGTH(b));

  dump(p1, LENGTH(a) + LENGTH(b));
  puts("\n----");
  dump(p2, LENGTH(a) + LENGTH(b));
  puts("\n----");
  dump(p3, LENGTH(a) + LENGTH(b));

  free(p1);
  free(p2);
  free(p3);

  return 0;
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1