您的位置:首页 > 编程语言 > C语言/C++

C语言使用注意事项(三)

2012-02-11 16:08 393 查看

转载于http://blog.csdn.net/yming0221/article/details/7237762

1、自己实现itoa(int)函数,由整型转换成字符串。

大家看看下面的是否有错?

[cpp]
view plaincopyprint?

/*************************************

* 整型转换成字符串
* *********************************/

char *itoa(int n)

{
#if 0
int tmp = n;

int cnt = 1;
while(tmp != 0)

{
tmp /= 10;
cnt++;
}
char *buf;
buf = (char *)malloc(cnt *
sizeof(char));

#else
char buf[20];

#endif
sprintf(buf,"%d",n);

return buf;
}

[cpp]
view plaincopyprint?

/*************************************

* 整型转换成字符串
* *********************************/

char *itoa(int n)

{
#if 1
int tmp = n;

int cnt = 1;
while(tmp != 0)

{
tmp /= 10;
cnt++;
}
char *buf;
buf = (char *)malloc(cnt *
sizeof(char));

#else
char buf[20];

#endif
sprintf(buf,"%d",n);

return buf;
}

/*************************************
* 整型转换成字符串
* *********************************/
char *itoa(int n)
{
#if 1
int tmp = n;
int cnt = 1;
while(tmp != 0)
{
tmp /= 10;
cnt++;
}
char *buf;
buf = (char *)malloc(cnt * sizeof(char));
#else
char buf[20];
#endif
sprintf(buf,"%d",n);
return buf;
}
但是要注意字符串使用完毕后记得使用free()函数来释放其内存。

所以说,函数的返回指针必须是静态分配的缓冲区或是由调用者传入的缓冲区或者是由被调用者使用malloc()函数动态申请的内存。

2、sizeof(char)的值是什么?

我们经常会看到下面的代码

[cpp]
view plaincopyprint?

char *p;
p=(char *)malloc(strlen(string)+1);

strcpy(p,string);

[cpp]
view plaincopyprint?

LNode *listp,*nextp;
for(listp = base;listp != NULL;listp = nextp)

{
nextp = listp->next;
free(listp);
}

LNode *listp,*nextp;
for(listp = base;listp != NULL;listp = nextp)
{
nextp = listp->next;
free(listp);
}


4、calloc()和malloc()的区别

其实calloc(m,n)实质上就是

p=malloc(m*n);

memset(p,0,m*n);

malloc()和calloc()申请的内存都可以使用free()来释放。

5、如果有人给你提出这个问题:假设两个整型变量,你如何不用额外的临时存储变量从而达到交换两个变量的值的目的

[cpp]
view plaincopyprint?

int a=23;
int b=45;
a ^= b;
b ^= a;
a ^= b;

[cpp]
view plaincopyprint?

#define assert(test)    ( test ? (void)0 : _Assert(__FILE__":"_STR(__LINE__)"" #test) )

#define assert(test)    ( test ? (void)0 : _Assert(__FILE__":"_STR(__LINE__)"" #test) )


作用个是在测试表达式为假(=0)时输出一条错误信息。

该函数只在程序调式时有用,在正常运行时不会执行,其是否起作用是通过宏来控制

关闭assert() #define NDEBUG

打开assert() #undef NDEBUG

8、给一个日期,计算是星期几的简洁代码。由Tomohiko Sakamoto 提供

[cpp]
view plaincopyprint?

int dayofweek(int y,
int m, int d)
/* 0 = Sunday */
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};

y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;

}

[cpp]
view plaincopyprint?

#define TRACE(var,fmt)   printf("TRACE: " #var " = " #fmt "\n",var)

#define TRACE(var,fmt)   printf("TRACE: " #var " = " #fmt "\n",var)


其中变量前的#用于和字符常量的连接。使用的一个实例。下面加入需要输出一个整型变量a

TRACE(a,%d);即可。

10、printf()的使用技巧>>如何让程序根据输出的结果自动实现输出的合理的宽度,而不是认为的做如下规定

printf("%5d",a);

下面这种用法可以达到预想的效果

printf("%*d",width,a);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: