Search code examples
c++cdebuggingformat-specifiers

format specifier for short integer


I don't use correctly the format specifiers in C. A few lines of code:

int main()
{
        char dest[]="stack";
        unsigned short val = 500;
        char c = 'a';

        char* final = (char*) malloc(strlen(dest) + 6);

        snprintf(final, strlen(dest)+6, "%c%c%hd%c%c%s", c, c, val, c, c, dest); 

        printf("%s\n", final);
        return 0;
}

What I want is to copy at

final [0] = a random char final [1] = a random char final [2] and final [3] = the short array final [4] = another char ....

My problem is that i want to copy the two bytes of the short int to 2 bytes of the final array.

thanks.


Solution

  • I'm confused - the problem is that you are saying strlen(dest)+6 which limits the length of the final string to 10 chars (plus a null terminator). If you say strlen(dest)+8 then there will be enough space for the full string.

    Update

    Even though a short may only be 2 bytes in size, when it is printed as a string each character will take up a byte. So that means it can require up to 5 bytes of space to write a short to a string, if you are writing a number above 10000.

    Now, if you write the short to a string as a hexadecimal number using the %x format specifier, it will take up no more than 2 bytes.