美文网首页
[习题11]数组和字符串:char *test = "

[习题11]数组和字符串:char *test = "

作者: AkuRinbu | 来源:发表于2018-09-16 14:01 被阅读13次

    使用教材

    《“笨办法” 学C语言(Learn C The Hard Way)》
    https://www.jianshu.com/p/b0631208a794

    ex11.c

    #include <stdio.h>
    
    int main(int argc,char *argv[])
    {
        int numbers[4] = {0};
        char name[4] = {'a'};
    
        //first, print them out raw
        printf("numbers: %d %d %d %d\n", numbers[0], numbers[1], numbers[2], numbers[3]);
    
        printf("name each: %c %c %c %c\n", name[0], name[1], name[2], name[3]);
    
        printf("name: %s\n", name);
    
        // set up the numbers
        numbers[0] = 1;
        numbers[1] = 2;
        numbers[2] = 3;
        numbers[3] = 4;
    
        // set up the name
        name[0] = 'Z';
        name[1] = 'e';
        name[2] = 'd';
        name[3] = '\0';
    
        // then print them out initialized
        printf("numbers: %d %d %d %d\n", numbers[0], numbers[1], numbers[2], numbers[3]);
    
        printf("name each: %c %c %c %c\n", name[0], name[1], name[2], name[3]);
    
        // print the name link a string
        printf("name: %s\n", name);
    
        // another way for use name
        char *another = "Zed";
    
        printf("another: %s\n", another);
    
        printf("another each: %c %c %c %c \n", another[0], another[1], another[2], another[3]);
    
        return 0;
    }
    

    Makefile

    CC=clang
    CFLAGS=-Wall -g
    
    clean:
        rm -f ex11
    

    run

    anno@anno-m:~/Documents/mycode/ex11$ make ex11
    clang -Wall -g    ex11.c   -o ex11
    anno@anno-m:~/Documents/mycode/ex11$ ./ex11
    numbers: 0 0 0 0
    name each: a   
    name: a
    numbers: 1 2 3 4
    name each: Z e d 
    name: Zed
    another: Zed
    another each: Z e d  
    

    说明

    • 数组如果只初始化了一个元素,剩下的元素会用0来填充;
    int numbers[4] = {0};
    numbers: 0 0 0 0
    第1个0 是初始化的那个元素
    剩余3个0是填充的0
    
    char name[4] = {'a'};
    name each: a  
    填充字符'\0'使得字符串被正确地结束了
    
    • 初始化字符串 以及 输出字符串
    char *another = "Zed";
    
    printf("another: %s\n", another);
    
    another: Zed
    

    to-do

    code

    //to-do-1
        int test_num[3] = {'0'};
        test_num[0] = 'a';
        printf("number %%d : %d\n", test_num[0]);
        printf("number %%c : %c\n", test_num[0]);
    
        //to-do-2
        char test_name[3] = {};
        test_name[0] = 't';
        printf("char %%d : %d\n", test_name[0]);
    
        //to-do-3
        char *test_another = "Hello world!";
        printf("%s\n", test_another);
    
    

    output

    number %d : 97
    number %c : a
    char %d : 116
    Hello world!
    
    • C语言中字符char就是一个小整数%d输出这个整数的值,%c输出这个字符;

    相关文章

      网友评论

          本文标题:[习题11]数组和字符串:char *test = "

          本文链接:https://www.haomeiwen.com/subject/hjzxnftx.html