はじめての C
各変数の 型のメモリサイズを表示するプログラムを作成せよ。
- /* ookisa */
- #include
- main()
- {
- printf("char %d\n", sizeof(char));
- printf("int %d\n", sizeof(int));
- printf("float %d\n", sizeof(float));
- printf("char * %d\n", sizeof (char *));
- }
座標系上の点と線をあらわす構造体 および 配列の メモリサイズを それぞれ表示するプログラムを作成せよ。
- /* ookisa.2 */
- #include
- main()
- {
- char buf[512];
- struct Point {
- float x;
- float y;
- };
- struct Line {
- struct Point a, b;
- };
- printf("buf %d\n", sizeof(buf));
- printf("struct Point %d\n", sizeof(struct Point));
- printf("struct Line %d\n", sizeof(struct Line));
- }
標準入力したファイルを ディスプレイに表示するプログラムを作成せよ。
関数 malloc() を使用すること。
関数 gets() を使うよりほかないか . . .
- /* yomikomi */
- #include
- #include
/* 関数 malloc() に必要 */ - #include
/* 関数 strlen() に必要 */ - main()
- {
- char *s, buf[512];
- int i;
- while (gets(buf) != NULL) { /*読み込む文字列がなくなるまで */
- s = (char *)malloc( strlen(buf) + 1 );
- /* strlen() : 文字列の長さを数える関数 ('\0'分、1つ追加しておく) */
- /* malloc() : メモリ割り当て関数 */
- /* (char *) : 関数 malloc() のキャスト (返り値は 文字変数のポインタ) */
- for ( i = 0 ; buf[i] != '\0' ; i++ ) {
- s[i] = buf[i];
- /* buf の文字列を 確保されたメモリ領域に移す */
- }
- s[i] = '\0'; /* 列の最後は '\0' */
- printf("%s\n", s);
- }
- }
上のプログラムを ポインタを使って改造せよ。
- /* yomikomi.2 */
- #include
- #include
- #include
- main()
- {
- char *s, *ps, *pd, buf[512];
- /* ps : 文字列 buf のポインタ */
- /* pd : メモリ領域 s のポインタ */
- while (gets(buf) != NULL) {
- ps = buf;
- pd = s = (char *)malloc( strlen(buf) + 1 );
- for ( ; ps != '\0' ; ) {
- *pd++ = *ps++; /* メモリ領域に文字列を移す */
- }
- *pd = '\0';
- printf("%s\n", s);
- }
- }
さらに 関数 strcpy() を使用して プログラムを改良せよ。
- /* yomikomi.3 */
- #include
- #include
- #include
- main()
- {
- char *s, buf[512];
- while (gets(buf) != NULL) {
- s = (char *)malloc( strlen(buf) + 1 );
- strcpy(s, buf);
- /* strcpy() : 文字列をメモリ領域にコピーする */
- /* 引数は コピー先のメモリ領域のポインタと もとの文字列のアドレス */
- printf("%s\n", s);
- }
- }
text: 金山典世さん(稚内北星)のページ