LoginSignup
1
0

More than 3 years have passed since last update.

mallocの宣言では何をしているのか

Last updated at Posted at 2019-09-04

はじめに

メモリの動的確保に使われるmalloc
実際に使うとき

example.c
#include <stdio.h>

void main(){
  int num;
  array=(int*)malloc(sizeof(int)*num);
}

のように宣言する。
この書き方は何をしているのかを考える。

追記

この記事はコメントを受けて一部を編集しました。

mallocの宣言では何をしているのか

上で書いた通り、mallocは

array=(int*)malloc(sizeof(int)*num);

のように宣言する。
後ろから考えるとsizeof(int)*numの部分は確保するメモリの大きさを指示している。ここではint型のサイズの値が入る領域を5つ分確保している。しかしsizeofを利用すると返ってきた値は、size_t型となってしまう。そこで(int)によってint型にキャストしている。 mallocの前半((int*))では、割り当てられたメモリを(int*)にキャストして割り当てられたメモリを4つずつに分割しているということである。

1
0
4

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
1
0