利用者:Senseequal/C言語

出典: フリー教科書『ウィキブックス(Wikibooks)』

名称[編集]

プロは「C言語」ではなく「C(スィー)」と呼ぶ。

Hello world[編集]

// hello.c
#include <stdio.h>

int main(void)
{
    puts("hello, world");
}
$ gcc -W -Wall -o hello hello.c && ./hello
Hello, world!

strlen[編集]

C言語を理解するのに、文字列は非常に重要です。

#include <stdio.h>
#include <string.h>
int main(void) {
    char *s = "Hello, world!\n";
    int len = strlen(s);
    fprintf(stdout, "%d\n", len);
    return 0;
}

コードはプリプロセッサを経てコンパイラに掛けられます。

#includeはプリプロセッサによって処理されます。

#include <stdio.h>はstdio.hをインクルードします。useと同じです。

string.hは文字列操作を扱います。

    char *s = "Hello, world!\n";

では、文字列 "Hello, world!\n" をchar型のポインタsに代入しています。

strlenはchar型のポインタを受け取り、長さをint型で返します。

14

文字列はchar型のポインタ。

fputsやfprintfに渡されている文字列もすべてchar型のポインタです。

#include <stdio.h>
int main(void) {
    char *s = "Hello, world!\n";
    fputs(s);
    return 0;
}
Hello, world!

strlenの自作[編集]

文字列の終端には '\0' が自動で付加されています。

strlenは、文字列の先頭から '\0' が現れるまでの長さを調べています。

#include <stdio.h>
int strlen(char *c) {
    int i = 0;
    while (*c != '\0') {
        i++;
        c++;
    }
    return i;
}
int main(void) {
    char *s = "Hello, world!\n";
    fprintf(stdout, "%d\n", strlen(s));
    return 0;
}
14

このプログラムを理解しましょう。

コマンドライン引数[編集]

#include <stdio.h>
int main(int argc, char **argv) {
    fprintf(stdout, "%d\n", argc);
    fprintf(stdout, "%s\n", argv[0]);
    return 0;
}

int argcには引数の数、char **argvには引数が入ります。@ARGVと同じです。

argv[0]にはプログラム名が入ります。$0と同じです。

入力[編集]

fgets()を使う。

#include <stdio.h>
int main(int argc, char **argv) {
    char s[8];
    fgets(s, sizeof s, stdin);
    fputs(s, stdout);
    return 0;
}

sizeof演算子は配列の長さを返します。

文字列は個々の文字を要素に持つ配列です。

#include <stdio.h>
int main(void) {
    char *s = "Hello, world\n";
    // "Hello, world!\n"
    fputs(s, stdout);
    // 'H'
    fprintf(stdout, "%c\n", *s);
    // 'H'
    fprintf(stdout, "%c\n", s[0]);
    s++;
    // "ello, world!\n"
    fputs(s, stdout);
    // 'e'
    fprintf(stdout, "%c\n", *s);
    *s++;
    // "llo, world!\n"
    fputs(s, stdout);
    // 'l'
    fprintf(stdout, "%c\n", *s);
    return 0;
}

終端には '\0' が埋め込まれています。