C语言,结构体中字符串的声明(采用字符指针还是字符数组) |
您所在的位置:网站首页 › 怎么定义字符串数组names › C语言,结构体中字符串的声明(采用字符指针还是字符数组) |
结构体中,字符串选项是用字符数组表示好,还是用字符指针表示好? typedef struct person{ char *name; int age; char sex[6]; }; 该结构体中name用的是指针而不是数组,所以需要给字符串在堆上申请内存然后再赋值;sex字符串用的是字符数组,因此可以给其赋值;
用字符指针的优势是:字符指针不会限制字符串的大小。如果用字符数组,需要提前决定字符串的长度。 上面的结构体中,name的值可以设无限长(前提时,要在堆上申请内存),而sex的字符串长度不能超过6。
下面是结构体对象创建的过程: man* creat(char *name, int age, char *sex) { man *i = malloc(sizeof(man)); i->name = strdup(name); i->age = age; i->sex = sex; return i; } strdup()函数会计算出字符串的长度,然后调用malloc函数在堆上申请相应的空间,最后把字符串的所有字符复制到堆上。
我们也可以在strdup()函数的基础上,实现一个有错误提示的strdup()函数 char * safe_strdup(const char *s) { char * retval = NULL; if (!s) { debug(LOG_CRIT, "safe_strdup called with NULL which would have crashed strdup. Bailing out"); exit(1); } retval = strdup(s); if (!retval) { debug(LOG_CRIT, "Failed to duplicate a string: %s. Bailing out", strerror(errno)); exit(1); } return (retval); }
对象创建的函数也可以随之做些更改: man* creat(char *name, int age, char *sex) { man *i = malloc(sizeof(man)); i->name = safe_strdup(name); i->age = age; i->sex = sex; return i; }
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |