如何在C中将int转换为字符串(char *)

时间:2014-11-21 10:31:45

标签: c arrays char integer character

我一直在寻找网络,我找不到任何东西。我目前有一个整数(int),我需要将其转换为char*(非char[])。到目前为止,我无法以任何方式工作。感谢

编辑: 我试着做以下没有运气

int i = 8;
char *charArray = i + '0';

编辑2: 因为我是C的新手,我在这里误解了一些东西。 我目前正在使用Pebble SDK(智能手表),我正在尝试从int转换为字符串以在函数text_layer_set_text()中传递它 当我使用格式时:char *example = "4"我的代码效果很好。虽然,无论我尝试在图层中传递我的注册的方式都不符合预期

6 个答案:

答案 0 :(得分:1)

问题不明确。

如果您想要char *作为通用指针:

#include <stdio.h>

int main(void)
{
    int x = 5;
    char *p = (char *)&x;

    printf("%d\n", *(int *)p);
    return 0;
}

如果您希望char *为字符串:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int x = 5;
    char *p = malloc(32);

    sprintf(p, "%d", x);
    printf("%s\n", p);
    free(p);
    return 0;
}

修改

  

我正在使用pebble(smartwatch sdk)和sprintf()函数   不支持

使用模数除法得到每个数字,然后反转字符串:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char *p = malloc(32);
    int i = 0, x = 5374;
    int temp, len;

    temp = abs(x); /* support for negatives */
    if (x < 0) p[i++] = '-'; /* support for negatives */
    do {
        p[i++] = '0' + temp % 10;
        temp /= 10;
    } while (temp);
    p[i] = '\0';
    if (x < 0) p++; /* support for negatives */
    len = strlen(p) - 1;
    for(i = 0; i < len / 2; i++) {
        temp = p[len];
        p[len] = p[i];
        p[i] = temp;
        len--;
    }
    if (x < 0) p--; /* support for negatives */
    printf("%s\n", p);
    free(p);
    return 0;
}

答案 1 :(得分:0)

  1. 声明并定义char *数组,分配内存。
  2. 使用sprintf()。查看手册页here
  3. 自己编写代码并告诉我们输出结果。


    编辑:

    您始终可以将int变量的地址转换为char *,但在使用char *时要非常小心。

    int i = 10;
    char * p = NULL;
    p = (char *)&i;
    

    如果您希望*p 表现为整数,请不要忘记在使用前将p投回int *。否则,你会感到惊讶。

答案 2 :(得分:0)

检查以下代码:

int a = 1234;
char *str = malloc(20);
sprintf(str, "%d", a);
printf("%s\n",str);

答案 3 :(得分:0)

如果您要使用char代替char*,那么您的首次尝试就会奏效。

int i = 8;
char c  = (char) (i + '0');    // c = "8"

从技术上讲,该方法无法保证工作 - 因为标准不会假设您使用的是ASCII,UNICODE或EBCDIC - 但除了这三个之外使用某些字符系统几乎闻所未闻,因此您是安全的。它也只适用于[0-9]范围内的整数。

答案 4 :(得分:0)

一个简单的方法是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

....
char buffer[32] = {'\0'};

int  a = 23;

itoa(a,buffer,10);   // here 10 means decimal
...

答案 5 :(得分:0)

你给出的工作示例,char * example =“8”// 这应该是char * example ='8';您正在创建指向char的指针,而不是字符串,chars数组。

你想要一个表示int作为ascii的字符数组吗? (或unicode?)

char buffer[32] = {'\0'}; //or char *buffer = malloc(32 * sizeof(char));  
int a = 10;
itoa(a, buffer,10);//convert an integer that can be represented by up to 32 chars

在pebble api看了一下(30秒)并发现了API sprintf版本,值得一看?     int snprintf(char * str, size_t n, const * fmt, ... )