简体   繁体   中英

Adding int as a char to a char[ ]

Sorry if the topic name isn't very clear I couldn't find a way to express it. So let's say i have this structure :

    struct filee 
    {
       ...
       int number;
       char filename[7];
    };
typedef struct filee filee;

and I want to initialize it with a function

void file_init(filee* x,int n)
{
    x->number=n;
    x->filename=(char)n+"ch.bmp"
}

but that doesn't really work so what I want is if for example I do this :

file_init(&randomFile,2);

It works this way:

randomFile.number=2;
randomFile.filename="2ch.bmp";

I hope that what I said is clear and thanks for the help!

You need to use snprintf()

int length;
int result;

length = sizeof(x->filename);
result = snprintf(x->filename, length, "%dch.bmp", x->number);
if ((result < 0) || (result >= length))
    error_TheTargetIsNotLargeEnough();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM