Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast int to char array in C

Is is possible to convert int to "string" in C just using casting? Without any functions like atoi() or sprintf()?

What I want would be like this:

int main(int argc, char *argv[]) {
    int i = 500;
    char c[4];

    c = (char)i;
    i = 0;
    i = (int)c;
}

The reason is that I need to generate two random ints (0 to 500) and send both as one string in a message queue to another process. The other process receives the message and do the LCM.

I know how to do with atoi() and itoa(). But my teachers wants just using cast.

Also, why isn't the following possible to compile?

typedef struct
{
    int x;
    int y;
} int_t;

typedef struct
{
    char x[sizeof(int)];
    char y[sizeof(int)];
} char_t;

int main(int argc, char *argv[])
{
    int_t rand_int;
    char_t rand_char;

    rand_int.x = (rand() % 501);
    rand_int.y = (rand() % 501);

    rand_char = (char_t)rand_int;
}
like image 835
Bodosko Avatar asked May 07 '13 22:05

Bodosko


People also ask

Can I cast int to char in C?

We can convert an integer to the character by adding a '0' (zero) character. The char data type is represented as ascii values in c programming. Ascii values are integer values if we add the '0' then we get the ASCII of that integer digit that can be assigned to a char variable.

Can I cast an int to a char?

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.

How do I cast to char?

To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char. the equivalent of the number 65 (It should be the letter A for ASCII).

How do you store an integer and character in the same array?

Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number. Separating integer into digits and accommodate it to a character array.


1 Answers

Of course it's not possible, because an array is an object and needs storage. Casts result in values, not objects. Some would say the whole point/power of C is that you have control over the storage and lifetime of objects.

The proper way to generate a string containing a decimal representation of an integer is to create storage for it yourself and use snprintf:

char buf[sizeof(int)*3+2];
snprintf(buf, sizeof buf, "%d", n);
like image 67
R.. GitHub STOP HELPING ICE Avatar answered Nov 15 '22 19:11

R.. GitHub STOP HELPING ICE