第一章 快速上手 [c和指针]

前记:最近在看《c和指针》-中文版,在这里留个记号也好监督一下自己。文中列写的代码均以经过调试运行。

以下是第一章的例程 1-1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_COLS 20
#define MAX_INPUT 1000

int read_column_numbers(int column[],int max);
void rearrange(char *output, char const *input, \
               int n_columns, int const columns[]);

int main(void)
{
    int n_columns;
    int columns[MAX_COLS];
    char input[MAX_INPUT];
    char output[MAX_INPUT];

    /*read the mark number*/
    n_columns = read_column_numbers(columns, MAX_COLS);//columns filled,columns SIZE
    /*read, deal with, print*/
    printf("Please input:\n");
    while( gets( input) != NULL)//gets use way
    {
        printf("Original input : %s \n", input);
        rearrange(output, input, n_columns, columns);//core code
        printf("Rearrange line: %s\n",output);
    }

    return EXIT_SUCCESS;

}
/*read mark line*/
int read_column_numbers(int columns[], int max)
{
    int num = 0;
    int ch;
    /*read mark number*/
    while(num < max && scanf( "%d",&columns[num]) == 1 \
          && columns[num] >= 0) //until non-interger
          num += 1;
    /*confirm even mark number*/
    if( num % 2 != 0)
    {
        puts("cuola! bu shi cheng dui de. ");
        exit(EXIT_FAILURE);
    }
    /*pass last part of that line*/
    
    while( (ch = getchar()) != EOF && ch != '\n')
        ;
    return num;

}
/*deal with */
void rearrange(char *output, char const *input,\
                int n_columns, int const columns[] )
{
    int col;
    int output_col;
    int len;

    len = strlen(input);
    output_col = 0;

    for( col = 0; col < n_columns; col += 2)
    {
        int nchars = columns[col + 1] - columns[col] + 1;

        if(columns[col] >= len || \
           output_col == MAX_INPUT - 1)
           break;


        if(output_col + nchars > MAX_INPUT - 1)
            nchars = MAX_INPUT - output_col - 1;

        strncpy( output + output_col, input + columns[col],\
                nchars);// core code

        output_col += nchars;
    }
    output[output_col] = '\0';
}

小结与思考:感觉这本书的写作视角很特别,c语言的写法也很独特很地道,不仅考虑程序功能而写考虑了代码性能、结构等我以前所不屑内容。从这个例子上来时,出了功能实现之外,还涉及了越界判断等,这是值得学习的。另外举一个小例子,例程中在结束输入列数对时(read_column_numbers函数中),程序思路是利用scanf()函数,使得一旦输入非整数(当然包括字符)其返回值就不为1,从而退出while()输入循环。在惊叹于其使用的巧妙时,也在违心的说上一句“这我也会,只是没想到”。仔细思考,你会发现对一些常见的函数理解还是不够深入,从而导致不会写出巧妙的代码。抽象成一句话:精湛的技艺源于深入挖掘!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值