Mohamed Moustafa
Mohamed Moustafa

Reputation: 124

How to initialize string in struct without using strcpy function?

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

Answers (3)

lost_in_the_source
lost_in_the_source

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

0___________
0___________

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

Vlad from Moscow
Vlad from Moscow

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

Related Questions