文字列のように 長さが異なる文字列を管理する時、 (char *)型の配列で管理すると、メモリを効率よく使えます。
| プログラム | 実行結果 |
|---|---|
#include <stdio.h>
#include <string.h>
char buf[30];/* 記憶域 */
int ipos = 0;/* 未使用位置 */
char * char_malloc(int size)
{
char *cp = buf + ipos; /* 未使用の位置を戻り値用変数へ記憶 */
ipos += size; /* 次に使う未使用位置を更新 */
return cp;
}
main()
{
char *a[3];/* ポインタの配列 */
char w[10];/* 入力用の文字列 */
int i;
for( i = 0; i < 3; i++){
printf("9文字以内で文字列入力>");
gets(w); /* 入力 */
a[i] = char_malloc( strlen( w ) + 1 );/* 未使用の記憶域取得 */
strcpy( a[i] , w );/* wが示すの文字列を、a[i]の領域へコピー */
}
for( i = 0; i < 3; i++){
printf("%d番目の文字列:%s\n", i+1 , a[i]);
}
}
|
10文字以内の文字列入力>ab 10文字以内の文字列入力>opqrstuvw 10文字以内の文字列入力>g 1番目の文字列:ab 2番目の文字列:opqrstuvw 3番目の文字列:g |
進む順番で説明します。⇒
(step1)