Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

動的メモリmallocの使い方

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);
}

あとがき

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

flowerrr__lily
東大電子情報工学科
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away