santiago deliotte
santiago deliotte

Reputation: 11

Why isn't strncpy working to copy a string to a variable of a struct?

I have the following struct in my code:

typedef struct
{
    uint64_t pulse;
    fp_t volume;
    fp_t factor; // Factor en pulsos / unidad de volumen
    char *unit_volume;
    char *unit_time;
} totalizer_t;

and it is initialized as static with 3 different variables:

static totalizer_t acm_config =
{
    .pulse = 1000,
    .volume.num = 1,
    .volume.res = 1,
    .factor.num = 1000, // pulsos/unidad_volumen.
    .factor.res = 0,
    .unit_volume = "LT",
    .unit_time = "S",
};

static totalizer_t rate_config =
{
    .pulse = 0,
    .volume.num = 0,
    .volume.res = 1,
    .factor.num = 1000,
    .factor.res = 0,
    .unit_volume = "LT",
    .unit_time = "S",
};

static totalizer_t ttl_config =
{
    .pulse = 12000,
    .volume.num = 1,
    .volume.res = 1,
    .factor.num = 1000, // pulsos/unidad_volumen.
    .factor.res = 0,
    .unit_volume = "LT",
    .unit_time = "S",
};

I want to modify the parameters .unit_volume and .unit_time from each struct. Because of this, I've made 2 functions like this:

void fm_factory_modify_units_time(char *p_str_time_units)
{
    strncpy(acm_config.unit_time, p_str_time_units, 1);
    strncpy(rate_config.unit_time, p_str_time_units, 1);
    strncpy(ttl_config.unit_time, p_str_time_units, 1);
}

void fm_factory_modify_units_volume(char *p_str_volume_units)
{
    strncpy(acm_config.unit_volume, p_str_volume_units, 2);
    strncpy(rate_config.unit_volume, p_str_volume_units, 2);
    strncpy(ttl_config.unit_volume, p_str_volume_units, 2);
}

unit_time is always a single char string, and unit_volume is always a 2 char string.

But when I try to use this function like this:

fm_factory_modify_units_volume("M3");

the acm_config.unit_volume doesn't change it's initial value, it remains being 'LT'. The same happens with the other function for the time units. I can change the other values from the struct. For example if I put rate_config.volume.res = 3 it changes from 1 to 3. So the problem is with the strings.

Using a debugger I can see when it enters the function and I know that the parameter p_str_volume_units is well assigned as for example, the string "M3".

I have tried to use other string.h functions to copy one string into the other like strcpy without the length check, or snprintf/sprintf like the following:

sprintf(rate_config.unit_volume, "%s", p_str_volume_units)

but it's still the same.

I want to use strings because it is compatible with other libraries I have made, but if it is impossible to change them, I will have to change it to an enum or something like that, but it will be hard.

If someone knows how to solve this problem, I will be very grateful.

Upvotes: 1

Views: 102

Answers (0)

Related Questions