简体   繁体   English

如何使用malloc将int变量转换为C中的char * array?

[英]how to convert a int variable to char *array in C with malloc?

I'm doing a school project and this problem came up. 我正在做一个学校项目,这个问题出现了。 by the way, i can't use library. 顺便说一句,我不能使用图书馆。

How to convert a int variable to char array? 如何将int变量转换为char数组? I have tried this but it didn't work, tried a lot of other things and even magic doesn't work... 我已经尝试过了,但是没有成功,尝试了很多其他事情,甚至魔术都不起作用...

char *r = malloc(sizeof(char*));
int i = 1;
r[counter++] = (char) i;

Can someone help me? 有人能帮我吗? Thank you for your time. 感谢您的时间。

In your code, you should allocate for char size and not char * . 在代码中,您应该分配char大小,而不是char * Please try with this code segment 请尝试使用此代码段

char *r = malloc(sizeof(char) * N); // Modified here
int i = 1;
r[counter++] = i & 0xff; // To store only the lower 8 bits.

You could also try this: 您也可以尝试以下方法:

char *r = malloc(sizeof(char));
char *s = (char*)&i; 
r[counter++] = s[0];

This is an other funny way to proceed and it allows you to access the full int with: s[0] , s[1] , etc... 这是另一种有趣的方式,它允许您使用s[0]s[1]等访问完整的int。

If you can't use the library, you can't use malloc . 如果您不能使用该库,则不能使用malloc

But this will work: 但这将起作用:

int i = 0;
char *p = (char *)&i;
p[0] = 'H';
p[1] = 'i';
p[2] = '!';
p[3] = '\0';
printf("%s\n", p);

Assuming your int is 32bit or more (and your char is 8). 假设您的int为32位或更高( char为8)。

It then follows that if you have: 然后,如果您具有:

int i[100];

You can treat that as an array of char with a size equal to sizeof (i) . 您可以将其视为大小等于sizeof (i)char数组。 ie

int i[100];
int sz = sizeof(i);     // probably 400
char *p = (char *)i;    // p[0] to p[sz - 1] is valid.

Do you mind losing precision? 你介意失去精度吗? A char is generally 8 bits and an int is generally more. 字符通常为8位,而整数通常为8位。 Any int value over 255 is going to be converted to its modulo 255 - unless you want to convert the int into as many chars as is takes to hold an int. 任何超过255的int值都将转换为255的模数-除非您希望将int转换为与容纳int一样多的字符。

Your title seems ot say that, but none of the answers give so far do. 您的标题似乎可以这么说,但是到目前为止,答案都还没有。

If so, you need to declare an array of char which is sizeof(int) / sizeof(char) and loop that many times, moving i >> 8 into r[looop_var] . 如果是这样,则需要声明一个char数组,它是sizeof(int) / sizeof(char)并循环多次,将i >> 8移到r[looop_var] There is no need at all to malloc, unless your teacher told you to do so. 除非您的老师告诉您这样做,否则根本不需要进行malloc。 In whch case, don't forget to handle malloc failing. 在这种情况下,请不要忘记处理malloc失败。

Let's say something like (I am coding this w/o compiling it, so beware) 让我们说一些类似的东西(我正在对此代码进行编译,因此请注意)

int numChars = sizeof(int) / sizeof(char);
char charArry[numChard];      // or malloc() later, if you must (& check result)
int convertMe = 0x12345678;
int loopVar;

for (loopVar = 0; loopvar < numChars)
{
  charArry[loopVar ] = convertMe ;
  convertMe = convertMe  >> 8;
}

You can use a union instead. 您可以改用union Assuming that sizeof int == 4 , 假设sizeof int == 4

typedef union {
    int i;
    char[4] cs;
} int_char;

int_char int_char_pun;
int_char_pun.i = 4;
for (int i = 0; i < 4; i++) {
    putchar(int_char_pun.cs[i]);
}

Be careful; 小心; int_char.cs usually won't be a null-terminated string, or it might be, but with length < 4. int_char.cs通常不是以空值结尾的字符串,也可能不是,但是长度小于4。

if you don't want to include the math library: 如果您不想包括数学库:

unsigned long pow10(int n);

void main(){
    char test[6] = {0};
    unsigned int testint = 2410;
    char conversion_started = 0;
    int i=0,j=0;float k=0;
    for(i=sizeof(test);i>-1;i--){
        k=testint/pow10(i);
        if(k<1 && conversion_started==0) continue;
        if(k >= 0 && k < 10){
            test[j++]=k+0x30;
            testint = testint - (k * pow10(i));
            conversion_started=1;
        }
    }
    test[j]=0x00;
    printf("%s",test);
}

unsigned long pow10(int n){
    long r = 1;
    int q = 0;
    if(n==0) return 1;
    if(n>0){
        for(q=0;q<n;q++) r = r * 10;
        return r;
    }
}

NOTE: I didn't care much about the char array length, so you might better choose it wisely. 注意:我不太在乎char数组的长度,因此您最好明智地选择它。

hmm... what is wrong with the code below 嗯...下面的代码怎么了

char *r = malloc(sizeof(char) * ARR_SIZE);
int i = 1;
sprintf(r,"%d",i);

printf("int %d converted int %s",i,r);

will it now work for you 现在会为您工作吗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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