c宏和strncpy

    技术2022-05-18  34

    转自http://bbs.pediy.com/showthread.php?t=130889&page=2

     

    1.宏中#的作用: 宏展开时, 如果没有遇到 # , 则会继续展开;

    代码如下:

    #include <stdio.h> int main () { #define Japan_EarthQuake 9.0 #define _ToStr(x) #x #define __ToStr(x) _ToStr(x) //输出Japan_EarthQuake is Japan_EarthQuake printf("Japan_EarthQuake is %s /n", _ToStr(Japan_EarthQuake)); //输出Japan_EarthQuake is 9.0 printf("Japan_EarthQuake is %s /n", __ToStr(Japan_EarthQuake)); system("pause"); return 0; }

    2.描述strncpy的行为:

     

    strncpy 的定义是:char* strncpy(char* dest, const char * source, size_t count);第一点:如果source串的长度比count长,只复制count长的串,后面不会补串结尾符'/0';第二点:如果count比source串要长,则长出的部分会全部补0;第三点:函数不检查dest的长度。如果dest分配的内存比count短,会溢出;

     

    #include <stdio.h> int main () { char a[8]="aaaaa"; char bb[12]="bbbbbbb"; char ccc[16]="ccccccccccc"; printf("a is %s /nbb is %s /nccc is %s /n",a,bb,ccc); strncpy(ccc,a,4); printf("ccc is %s /n", ccc); strncpy(a,ccc,10); printf("a is %s /n", a);//输出aaaacccccc+乱码 strncpy(ccc,bb,10); printf("ccc is %s /n", ccc); system("pause"); return 0; } 

     


    最新回复(0)