LoginSignup
5

More than 3 years have passed since last update.

動的メモリmallocの使い方

Last updated at Posted at 2020-02-29

malloc

  • みんなの敵malloc
  • わからなくなりがちだからまとめ
  • コロナと一緒に倒しちゃいましょう!
  • #include < stdlib.h> です!
  • 0で初期化したい場合はcallocを使う

基本形

ポインタ = (型*)malloc(sizeof(型) * 大きさ)

例えば、

int *p = (int*)malloc(sizeof(int)*100);
free (p);

#include <stdio.h>
#include <stdlib.h>
int main(){
  int arraySize = 5;
  int* p;
  p = (int*)malloc(sizeof(int)*arraySize);

  int i;
  for(int i=0; i<arraySize; i++) p[i] = 2*i;
  for(int i=0; i<arraySize; i++) printf("p[%d] = %d\n", i, p[i]);

  free(p);
  return 0;
}

出力は
p[0] = 0
p[1] = 2
p[2] = 4
p[3] = 6
p[4] = 8

配列のコピー

  • #include < string.h>が必要です

memcpy(dest, src, size)

int a[] = {1, 2, 3, 4, 5};
int *b = (int*)malloc(sizeof(int)*5);
memcpy(b, a, sizeof(int) * 5);

malloc()関数

使い方の例

int *ptr = (int*)malloc(sizeof(int)*10);

if(ptr == NULL) exit(1); //メモリ確保に失敗した時はNULL

ptr[0] = 123;
ptr[1] = 555;

free(ptr);

構造体で使う

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

// point構造体の定義は省略

struct point *init_point(int x, int y){
  struct point *ptr = malloc(sizeof(struct point));

  ptr->x = x;
  ptr->y = y;

  return ptr;
}

// または

struct point *init_point(int x, int y){
  struct point *ptr = malloc(sizeof(struct point));

  *ptr = (struct point){.x = x, .y = y};
  return ptr;
}

int main(){
  struct point *ptr = init_point(10, 20);

  printf("%d\n", ptr->x);
  printf("%d\n", ptr->y);
}

あとがき

コロナのせいで予定なくなって暇になって書きました
超低クオリティですみません!!!!

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
5