C言語に関してです。(コインなくて申し訳ないです。 文字列を標準入力し、空白や文字数字以外があればそこで一旦格納するというものです。(例)aaa(空白)bbb⇒aaaとbbbが格納される。
C言語に関してです。(コインなくて申し訳ないです。 文字列を標準入力し、空白や文字数字以外があればそこで一旦格納するというものです。(例)aaa(空白)bbb⇒aaaとbbbが格納される。 1.以下のプログラムにおいて*words[WORDLEN]を動的メモリの確保に用いるのはおかしいですか? 2.char *words[WORDNUM] とシステムで確保された動的メモリが,どのような関係にあるか,またそれを図示せよ。とはどのような意味だとおもいますか? <条件> 動的メモリ割当のタイミングは,readword() 関数を呼んだ直後で,readword() の戻り値を用いて行うこと。 なお,main() 関数の readword() 関数で用いる文字列については,固定長の文字型配列とし,それから動的メモリに格納すること。 <プログラム> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #define WORDLEN 64 #define WORDNUM 200 #define IN 1 #define OUT 0 int readword(char word[WORDLEN]){ char cc ; int i, flag ; flag = OUT ; i=0; while(!feof(stdin)) { cc = getchar() ; if (isalpha(cc) || isdigit(cc)){ /* you may use "isalnum()" */ flag = IN ; word[i] = cc ; i++ ; if (i >= WORDLEN) return 0 ; } else if (flag == IN){ word[i] = '\0' ; return i ; } } return EOF ; } int main(void){ char *words[WORDNUM] ; char word[WORDNUM][WORDLEN]; int i, j ; int lengh ; i=0; printf("Enter words : ") ; while (!feof(stdin)){ lengh = readword(word[i]) ; if (lengh == 0) printf("No more space in readword !!!\n") ; /* Normally, you shold use fprintf(stderr, ....) at caution. */ else if (lengh == EOF) printf("End of file!!!\n") ; else { words[i] = (char*)malloc(sizeof(char)*(lengh+1)); strcpy(words[i],word[i]); printf("words[%d] = %s\n",i,words[i]); printf("i=%d, \"%s\"=%d\n", i, words[i],lengh); i++; } } printf("Dump stored words : \n") ; for (j = 0 ; j < i ; j++) printf ("%d:%s\n", j, words[j]) ; for (j = 0;j < i;j++ ){ printf(" words[%d] = %p\n",j,words[j]); printf("*words[%d] = %c\n",j,*words[j]); } printf("\nBye....\n") ; free(words); return 0 ; }