【課題6−2】

 

(プログラム例)

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main(void) {

         char s[101];

         char **table;  /* char型ポインタへのポインタtableを宣言 */

         int i, n;

 

         /* 入力する文字列の数を入力 */

         printf("Input number of string: ");

         scanf("%d", &n);

        

         /* 文字列の数分のchar型ポインタを格納するためのメモリを確保 */

         table = (char **)malloc(sizeof(char *) * n);

         if (table==NULL) {

                 return 1;

         }

         for (i = 0; i < n; i++)

                 table[i] = NULL;

 

         for (i = 0; i < n; i++) {

                 printf("strint #%d: ", i+1);

                 scanf("%100s", s); /* 入力文字列をsに格納 */

                 /* 入力文字列の長さに応じて必要なメモリを確保 */

                 table[i]=(char *)malloc(sizeof(char)*(strlen(s)+1));

                 if (table[i]==NULL) {

                          printf("Failed to allocate memory.\n");

                          goto FREE;

                 }

                 strcpy(table[i], s); /* 入力文字列をtableの要素にコピー */

         }

         for (i = 0; i < n; i++)

                 printf("%s\n", table[i]);

 

FREE:

         for (i = 0; i < n; i++)        /* tableの各要素(ポインタ)のメモリ解放 */

                 free(table[i]);        

         free(table);                     /* tableのメモリ解放 */

 

         return 0;

}

 

(実行結果)

Input number of string: 12<enter>

strint #1: January<enter>

strint #2: February<enter>

strint #3: March<enter>

strint #4: April<enter>

strint #5: May<enter>

strint #6: June<enter>

strint #7: July<enter>

strint #8: August<enter>

strint #9: September<enter>

strint #10: October<enter>

strint #11: November<enter>

strint #12: December<enter>

January

February

March

April

May

June

July

August

September

October

November

December