[英]How to initialize string in struct without using strcpy function?
有沒有手動方法可以在struct中初始化字符串? 我曾經使用strcpy函數在struct中初始化字符串,例如:
typedef struct {
int id;
char name[20];
int age;
} employee;
int main()
{
employee x;
x.age=25;
strcpy(x.name,"sam");
printf("employee age is %d \n",x.age);
printf("employee name is %s",x.name);
return 0;
}
嚴格來說
strcpy(x.name,"sam");
不是初始化。
如果要談論初始化,那么您可以按照以下方式進行
employee x = { .name = "sam", .age = 25 };
要么
employee x = { .name = { "sam" }, .age = 25 };
這等效於以下初始化
employee x = { 0, "sam", 25 };
要么
employee x = { 0, { "sam" }, 25 };
或者,您甚至可以使用employee
類型的復合文字來初始化對象x
盡管這樣效率不高。
否則,如果不是初始化而是結構的數據成員的分配,那么實際上您至少必須使用strcpy
或strncpy
。
您可以編寫自己的strcpy
版本:
void mycopy(char *dest, const char *source, size_t ndest)
{
assert(ndest != 0);
while (--ndest > 0 && (*dest++ = *source++))
;
}
您不再使用strcpy
。 另外它更安全。
最大-包括尾隨零
char *mystrncpy(char *dest, const char *src, size_t max)
{
char *tmp = dest;
if (max)
{
while (--max && *src)
{
*dest++ = *src++;
}
*dest++ = '\0';
}
return tmp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.