はじめての C

各変数の 型のメモリサイズを表示するプログラムを作成せよ。

  1. /* ookisa */
  2. #include
  3. main()
  4. {
  5. printf("char %d\n", sizeof(char));
  6. printf("int %d\n", sizeof(int));
  7. printf("float %d\n", sizeof(float));
  8. printf("char * %d\n", sizeof (char *));
  9. }

座標系上の点と線をあらわす構造体 および 配列の メモリサイズを それぞれ表示するプログラムを作成せよ。

  1. /* ookisa.2 */
  2. #include
  3. main()
  4. {
  5. char buf[512];
  6. struct Point {
  7. float x;
  8. float y;
  9. };
  10. struct Line {
  11. struct Point a, b;
  12. };
  13. printf("buf %d\n", sizeof(buf));
  14. printf("struct Point %d\n", sizeof(struct Point));
  15. printf("struct Line %d\n", sizeof(struct Line));
  16. }

標準入力したファイルを ディスプレイに表示するプログラムを作成せよ。
関数 malloc() を使用すること。

関数 gets() を使うよりほかないか . . .

  1. /* yomikomi */
  2. #include
  3. #include /* 関数 malloc() に必要 */
  4. #include /* 関数 strlen() に必要 */
  5. main()
  6. {
  7. char *s, buf[512];
  8. int i;
  9. while (gets(buf) != NULL) { /*読み込む文字列がなくなるまで */
  10. s = (char *)malloc( strlen(buf) + 1 );
  11. /* strlen() : 文字列の長さを数える関数 ('\0'分、1つ追加しておく) */
  12. /* malloc() : メモリ割り当て関数 */
  13. /* (char *) : 関数 malloc() のキャスト (返り値は 文字変数のポインタ) */
  14. for ( i = 0 ; buf[i] != '\0' ; i++ ) {
  15. s[i] = buf[i];
  16. /* buf の文字列を 確保されたメモリ領域に移す */
  17. }
  18. s[i] = '\0'; /* 列の最後は '\0' */
  19. printf("%s\n", s);
  20. }
  21. }

上のプログラムを ポインタを使って改造せよ。

  1. /* yomikomi.2 */
  2. #include
  3. #include
  4. #include
  5. main()
  6. {
  7. char *s, *ps, *pd, buf[512];
  8. /* ps : 文字列 buf のポインタ */
  9. /* pd : メモリ領域 s のポインタ */
  10. while (gets(buf) != NULL) {
  11. ps = buf;
  12. pd = s = (char *)malloc( strlen(buf) + 1 );
  13. for ( ; ps != '\0' ; ) {
  14. *pd++ = *ps++; /* メモリ領域に文字列を移す */
  15. }
  16. *pd = '\0';
  17. printf("%s\n", s);
  18. }
  19. }

さらに 関数 strcpy() を使用して プログラムを改良せよ。

  1. /* yomikomi.3 */
  2. #include
  3. #include
  4. #include
  5. main()
  6. {
  7. char *s, buf[512];
  8. while (gets(buf) != NULL) {
  9. s = (char *)malloc( strlen(buf) + 1 );
  10. strcpy(s, buf);
  11. /* strcpy() : 文字列をメモリ領域にコピーする */
  12. /* 引数は コピー先のメモリ領域のポインタと もとの文字列のアドレス */
  13. printf("%s\n", s);
  14. }
  15. }

text: 金山典世さん(稚内北星)のページ