0

Can anyone please explain?

char *s = get_string("s: ");

    if (!s)
{
    return 1;
}
// allocate memory for another string
char *t = malloc((strlen(s) +1) * sizeof(char));

if (!t)
{
    return 1;
}

if I understand correctly.
After an input from a user a memory has been allocated for "*s".

Then we declare a new variable called "t" that's going to store the address of a character.
char *t = malloc((strlen(s) +1) * sizeof(char));

"Take length of s. Add 1 byte for \0. Call it t and allocate a separate memory for this."

But why do we need sizeof(char) here? Didn't we already know the length of this string form *s?

0

We use sizeof(char) just for uniformity of the code. It is 1 on all systems I know of, so you could omit it without any change. Its value is not specified in the C standard (in theory, a Chinese system might use 16 or 32 bit char because their characters are multi-byte in any encoding - but they are likely to not change char but create their own type instead).

What we want to express is "allocate space for n items of m bytes per item". We want to express that the number represents bytes, not items (which, again, is the same number in this case). Some APIs express this explicitly. For example, calloc and fread expect two numbers, the number of items and the bytes per item, even if the result is largely the same as allocating/reading the product of the two numbers.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .