pradipta
pradipta

Reputation: 1746

Byte allocation in short unsigned data

kindly check the following program

#include <stdio.h>
#include<stdlib.h>
int main()
{
        char *Date= NULL;
        unsigned short y=2013;
        Date =  malloc(3);
        sprintf((char *)Date,"%hu",y);  
        printf("%d %d %d %d %d \n",Date[0],Date[1],Date[2],Date[3],Date[4]);

        printf("%s %d %d",Date,strlen(Date),sizeof(y));
}

output:
50 48 49 51 0
2013 4 2

How I am getting the string length 4 instead 2,as I am putting a short integer value into the memory so it should be occupied in 2 byte of memory.But how it is taking 4 byte.

How each byte getting 2 0 1 3 from the input, instead 20 in one byte and 13 in another byte.

I want to put 20 to one byte and 13 to another byte.How to do that.kindly tell something

Kindly give some answer.

Upvotes: 0

Views: 171

Answers (2)

P.P
P.P

Reputation: 121347

You are invoking undefined behaviour.

You have allocated only 3 bytes for Date and storing 5 bytes.

Four bytes for 2013 and 1 NUL byte. So you should allocate at least 5 bytes if you want to store 2013.


If you want to transfer a stream of bytes then I suggest you do in the following way:

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
        unsigned char *Date= NULL;
        unsigned short y=2013;
        unsigned char *p;

        p = (unsigned char*) &y;
        Date =  malloc(3);
        Date[0] = *p;
        Date[1] = *(p+1);
        Date[2] = 0;

        printf("%s %d %d",Date,strlen(Date),sizeof(y));
}

This outputs:

� 2 2

The strange char is because interpreting some byte values as a string. Plain char may be signed or unsigned depending on your implementation. So use unsigned char to avoid incorrect interpretation of bytes.

Upvotes: 3

Taurre
Taurre

Reputation: 333

As indicate by its name, the sprintf function write a formated string. So, your number 2013 is converted to "2013" (a 5 character string).

Upvotes: 5

Related Questions