免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 974 | 回复: 0
打印 上一主题 下一主题

第四周:C语言 预处理 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-21 08:41 |只看该作者 |倒序浏览
gcc -S main.c可以生成汇编文件
推荐书籍:《编码的奥秘》《算法导论》

课堂笔记:
12、C预处理器

文件包含
#include "文件名"
#include <文件名>

宏替换

#define 名字 替换文本

#define max(A, B) ((A) > (B) ? (A) : (B))

#undef

条件包含

#if
#else or #elif
#endif

defined(identifier)
defined identifier

#if !defined(identifier)
#define identifier
    ...
    ...
#endif

#ifdef
#ifndef

13、函数的实现(可选)



编程实例:
1.用递归列举菲波纳切队列:
#include <stdio.h>
#include <stdlib.h>

int feibit(int m, int array[])
{
    int ret;
    if(m == 1 || m == 2)
    {
        array[m]=1;
        return array[m];
    }else
    {
        array[m] = feibit(m-1,array) + feibit(m-2,array);
        return array[m];
    }


}

main(void)
{
    int n = 15;
    int array[20];
    int i;
    feibit(n,array);
    for(i=1;i<n;i++)
        printf("%d ",array[i]);

}

2.自己编写strncpy,strncmp,strncat:
::::::::::::::
main.c
::::::::::::::
#include "mystr.c"
#include <string.h>


main(void)
{
    char dest[64]="hello,world,I am YEP";
    char *pdest;
    char *s="Basketball";
/*
    pdest = mystrncpy(dest,s,5);
    printf("%s\n",pdest);
*/
    pdest = mystrncpy(dest,s,6);
    printf("%s\n",pdest);

    pdest = mystrncat(dest,s,7);
//    pdest = strncat(dest,s,3);
    printf("%s\n",pdest);

    printf("%d\n", mystrncmp(dest,s,5));
    printf("%d\n", mystrncmp(dest,s,10));

}    

::::::::::::::
mystr.c
::::::::::::::
#include <stdio.h>
#include <stdlib.h>


char *mystrncpy(char *d, const char *s, size_t size)
{
    int i;
    int flag=0;
    for(i=0;i<size;i++)
        {
        if(s[i]=='\0')
            flag = 1;
        if(flag == 1)
            d[i]=' ';
        else
            d[i]=s[i];
        }
    return d;
}

char *mystrncat(char *d, const char *s, size_t size)
{
    int i=0;
    int k;
    while(d[i] != '\0')
        i++;
    for(k=0,i;k<size;k++,i++)
        d[i]=s[k];
    d[i]='\0';
    return d;

}

int mystrncmp(char *d, const char *s, size_t size)
{
    int i;
    for(i=0;i<size;i++)
    {
        if(d[i]!=s[i])
            return (d[i] - s[i]);
    }
    return 0;
}





您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP