Reputation: 124
Is there any manual way to initialize the string in struct ? I used to initialize string in struct using strcpy function such as:
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;
}
Upvotes: 0
Views: 2221
Reputation: 11237
You can write your own version of strcpy
:
void mycopy(char *dest, const char *source, size_t ndest)
{
assert(ndest != 0);
while (--ndest > 0 && (*dest++ = *source++))
;
}
You're not using strcpy
anymore. Plus it is safer.
Upvotes: -1
Reputation: 67476
max - including trailing zero
char *mystrncpy(char *dest, const char *src, size_t max)
{
char *tmp = dest;
if (max)
{
while (--max && *src)
{
*dest++ = *src++;
}
*dest++ = '\0';
}
return tmp;
}
Upvotes: -1
Reputation: 310940
Strictly speaking this
strcpy(x.name,"sam");
is not an initialization.
if to speak about the initialization then you can do it the following way
employee x = { .name = "sam", .age = 25 };
or
employee x = { .name = { "sam" }, .age = 25 };
This is equivalent to the following initialization
employee x = { 0, "sam", 25 };
or
employee x = { 0, { "sam" }, 25 };
Or you even can use a compound literal of the type employee
to initialize the object x
though that is not efficient.
Otherwise if is not an initialization but an assignment of the data member of the structure then indeed you have to use at least strcpy
or strncpy
.
Upvotes: 7