『C言語ポインタ完全制覇 (標準プログラマーズライブラリ)』の勉強だよ。
mallocを用いた可変長配列
/* ======================= */
/* === Include library === */
/* ======================= */
#include <stdio.h>
#include <stdlib.h>
/* ================= */
/* === Functions === */
/* ================= */
int main(void)
{
char buf[256];
int size;
int *variable_array;
int i;
printf("Input Array Size: ");
/* Read Data from STDIN */
fgets(buf, 256, stdin);
sscanf(buf, "%d", &size);
variable_array = malloc(sizeof(int) * size);
for (i = ; i < size; ++i)
{
variable_array[i] = i;
}
for (i = ;i < size; ++i)
{
printf("variable_array[%d] : %d\n", i, variable_array[i]);
}
return ;
}
可変長配列の配列の一つの例
/* ======================= */
/* === Include library === */
/* ======================= */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ================= */
/* === Functions === */
/* ================= */
void read_slogan(FILE *fp, char **slogan)
{
char buf[1024];
int i;
for (i = ; i < 7; i++)
{
fgets(buf, 1024, fp);
buf[strlen(buf) - 1] = '\0';
slogan[i] = malloc(sizeof(char) * (strlen(buf) + 1));
strcpy(slogan[i], buf);
}
}
int main(void)
{
char *slogan[7];
int i;
read_slogan(stdin, slogan);
for (i = ; i < 7; ++i)
{
printf("%s\n", slogan[i]);
}
return ;
}