c基本程序题

一、写出strcpy函数
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char * myStrcpy(char *desStr,const char *srcStr)
{
    assert(desStr !=NULL && srcStr != NULL);
    char *desAdder;
    while( *srcStr != '\0')
    {
        *desStr = *srcStr;
        *desStr++;
        *srcStr++;
    }
    return desAdder;
}
int main()
{
    char *str1 = "0123456789";
    char *test = (char *)malloc(strlen(str1)+1);
    myStrcpy(test,str1);
    printf("test string is :%s\n",test);
    return 0;
}
二、计算出一个整形包含多少个一
#include <stdio.h>

int Count(unsigned int number)
{
    int sum = 0,n;
    if(number == 0)
                    return 0;
    /*while(number)  // 方法1,效率低
    {
        if(number % 2  == 1)
                        sum ++;
        number /= 2;
    }*/

    for(n =0 ; n<8 ;n++)  // 方法二,效率高
    {
        if((number>>n)&0x01)
                        sum++;
    }
    return sum;
}
int main()
{
    int  n;
    scanf("%d",&n);
    printf("%d\n",Count(n));
    return 0;
}
三、判断当前系统的大小端序
#include <stdio.h>
union test
{
    int a;
    char c;
}endian;


static union
{
    char c[4];
    unsigned long l;
}endian_test = {{'l',' ',' ',' b'}};

#define ENDIAN_TEST ((char )endian_test.l)
int main()
{
    // 方法一:
    endian.a = 0x12345678;
    if(endian.c == 0x78)
    {
        printf("the cpu is little endian\n");
    }else
    {
        printf("the cpu is big endian\n");
    }

    // 方法二:
    int a = 0x12345678;
    char p = *(&a);
    if(p == 0x78)
    {
        printf("the cpu is little endian\n");

    }else
    {

        printf("the cpu is big endian\n");
    }

    // 方法三:
    printf("%c\n",ENDIAN_TEST); // 输出'l'为小端序,输出'b'为大端序
    return 0;
}
四、将一个字符串循环右移n位
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void LoopRight(char *Str,int len)
{
    char temp[strlen(Str)+1];
    strncpy(temp,Str+strlen(Str)-len,len);
    strcpy(temp+len,Str);
    temp[strlen(Str)] = '\0';
    strcpy(Str,temp);
}
int main()
{
    LoopRight(str,5);
    printf("%s\n",str);
    return 0 ;
}
五、写出一个宏MAX 计算两个数的最大值

a) #define MAX(A,B) A>B?A:B   // 错误版本
b) #define MAX(A,B) (A)>(B)?(A):(B) //不能处理 MAX(a++,b) 这种情况,a被加了两次
c)#define MAX(A,B)\
            ({\
                 int _a = A;\
                 int _b = B;\
                 (_a)>(_b)?(_a):(_b);\
            })//不能处理浮点型的情况

d最终版本)#define MAX(A,B)\
            ({\
                 typeof(a) _a = A;\
                 typeof(b) _b = B;\
                 (_a)>(_b)?(_a):(_b);\
            })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值