【问题标题】:Converting an integer to a character array i.e. 123 => '123'将整数转换为字符数组,即 123 => '123'
【发布时间】:2016-02-28 11:44:38
【问题描述】:

此代码的目的是将整数转换为字符数组。
以下代码导致垃圾输出。不过,这似乎是对的。有什么建议吗?

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

char* intToChar(int product);

int main()
{   
    printf("%s\n", intToChar(213));

    return 0;
}

char* intToChar(int product)
{
    int temp = product;
    int c = 0;
    char* morphed;

    while(temp)
    {
        temp /= 10;
        c++;
    }
    /printf("c : %d\n", c);//db
    morphed = malloc(sizeof(char) * c);

    temp = product;
//  printf("temp : %d\n", temp);//db
    c -= 1;
    while(temp)
    {
        morphed[c] = (char)temp % 10;
        //printf("c[] %c\n", morphed[c]);//db
        c -= 1;
        temp /= 10;
    }

    return morphed;
}

【问题讨论】:

  • 您需要将'0'添加到输出中的每个数字以获取数字'0'而不是值为0的字符。
  • 您有内存泄漏。和 undefined behavior 因为你不终止“字符串”。您是否有理由必须制作自己的函数,而不是仅使用 printf 函数之一(如直接使用 printfsnprinf 如果您需要字符串)?
  • 您需要在字符串末尾添加空终止字符'\0' 才能使用printf()。不要忘记为它分配空间! morphed = malloc(sizeof(char) * (c+1));morphed[c]='\0';
  • 添加 '0' 成功了!谢谢!
  • 输出仍然不正确。 int temp = 3 并不意味着 (char)temp 等于 '3'。

标签: c casting malloc


【解决方案1】:

首先要考虑到 0 是一个有效的整数,也应该转换为字符串。

int 类型的对象也可以是负数。

而且您需要将数字的每个数字转换为其字符表示。

结果字符串应附加终止零。

函数可以如下面的演示程序所示

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

char * intToChar( int product )
{
    const int Base = 10;

    int temp = product;
    int n = 0;
    char* morphed;

    do { ++n; } while ( temp /= Base );

    if ( product < 0 ) ++n;

    morphed = malloc( ( n + 1 ) * sizeof( char ) );

    morphed[n--] = '\0';

    temp = product;

    do { morphed[n--] = '0' + abs( temp % Base ); } while ( temp /= Base );

    if ( product < 0 ) morphed[n] = '-';

    return morphed;
}

int main( void ) 
{
    char *p;

    p = intToChar( 0 );

    puts( p );

    free( p );

    p = intToChar( 123 );

    puts( p );

    free( p );

    p = intToChar( -123 );

    puts( p );

    free( p );

    return 0;
}

它的输出是

0
123
-123

【讨论】:

    【解决方案2】:

    我看到您基本上想将整数转换为字符数组或字符串。我看不出你创建自己的函数来这样做的原因。你可以使用sprintf:

    int a = 213;
    char str [20];
    sprintf (str, "%d", a);
    

    你也可以使用snprintf,这样更安全。


    作为@FUZxxi,在输出中为每个数字添加一个零将起作用。

    【讨论】:

      【解决方案3】:

      以下修改

      morphed = malloc(sizeof(char) * (1+c) ); /* leave room for a '\0' at end */
      memset( morphed, 0, sizeof(char) *(1+c) ); /* set to 0.*/
      

      以后

      morphed[c] = (char)temp % 10 + '0';
      

      这会将 ascii '0' 值添加到您计算的每个数字

      the digit '0' is ascii 48
      the digit '1' is ascii 49
      ...
      the digit '9' is ascii 57
      

      对于其他字符集...

      char digits[] = "01234567890";
      ...
      morphed[c] = digits[ temp % 10];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 2010-12-05
        相关资源
        最近更新 更多