malloc関数とは
malloc関数は指定したバイト分のメモリを確保する関数です。
#includeを追加
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
メモリを動的に確保する際に使う
int n = 47;
int *p1, *p2;
double *p3;
char *p4;
p1 = (int *)malloc(sizeof(int) * 128);
p2 = (int *)malloc(sizeof(int) * n);
p3 = (double *)malloc(sizeof(double) * 128);
p4 = (char *)malloc(sizeof(char) * 256);
if(p1 == NULL){
printf("Memory allocation error.\n");
return 1;
}
for(i=0; i<128; i++){
scanf("%d", &p1[i]);
}
free(p1); free(p2); free(p3); free(p4);
return 0;
構造体型式の場合
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
struct abc{
char name[15];
int pop;
double den;
};
int main(void){
struct abc *p1;
p1 = (struct abc *)malloc(sizeof(struct abc) * 47);
if(p1 == NULL){
printf("Memory allocation error.\n");
}
for(i=0; i<47; i++){
scanf("%d", &p1[i].pop);
}
free(p1);
return 0;
}