设为首页 加入收藏

TOP

strcpy函数的实现
2013-07-23 09:05:09 来源: 作者: 【 】 浏览:157
Tags:strcpy 函数 实现
    strcpy函数的实现,函数可以用于链式表达式,下面我们来看一下实现方法:
    #include<stdio.h>
    #include<assert.h>
    #define N 100
    char *my_strcpy(char *dest,char *src)
    {
    //返回值保存
    char *p = dest;
    //检查入参,使程序健壮
    assert(dest != NULL || src !=NULL);
    //注意越界
    while((*dest++ = *src++) != '\0');
    //返回字符指针,是函数可以用于链式表达式,增强可用性
    return p;
    }
    int main()
    {
    char str1[N];
    char *str2 = "My future is wonderful.";
    printf("%s\n",my_strcpy(str1,str2));
    return 0;
    }
    进项目笔试中碰到的一个题目,求优化。
    [cpp
    #include<stdio.h>
    #include<assert.h>
    #define N 100
    /* 实现查找一个数组小于平均值的所有元素
    number为要查找的数组,n元素个数,store返回的数组,
    函数返回小于平均值的个数
    */
    int iFindSmallerNum(int number[],int n,int store[])
    {
    int i,j=0,sum = 0,ave;
    *store = *store;
    assert(n>0);
    for(i=0; i<n; i++)
    sum += number[i];
    ave = sum / n;
    for(i=0;i<n;i++)
    {
    if(number[i]<ave)
    store[j++] = number[i];
    }
    return j;
    }
    int main()
    {
    int number = {10,12,14,16,18,20,22,24,26,28};
    int store[N];
    int n,no = iFindSmallerNum(number,10,store);
    printf("%d\n",no);
    for(n = 0; n<no;n++)
    printf("%d\t",store[n]);
    return 0;
    }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇在c++11中讨论nullptr和NULL 下一篇从递推问题到递推公式

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: