0

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;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

3 Answers3

7

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-1

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.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
-1

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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74