c - 将 int 转换为 char 数组的函数,一些问题

标签 c arrays null char

此代码需要获取一个 int 数字并将其转换为表示该数字的 char 数组: 例如:

数字 324

转换为: 喜欢:

char newstr [6] = {'3','2','4','\0','\0','\0'};
  1. 我认为'\0' 是空的,对吗?

我的代码有什么问题?

另外,我如何才能将其更改为获取 int 数字并返回呈现它的 char 数组的函数?

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

void main ()
 {
   int value = 324;
   char str [6];
   char newstr [6];
   int pointer, i = 0;

   for(i=0; value>0; i++)
     {
        str[i] = value%10 + '0';
        value /=10;
     }

        str[i] = '\0';

   for(i=5; i>-1; i--)
     {
       if(str[i]!='\0')
        {
         newstr[pointer] = str[i];
         pointer++;  
        }
     }

   for (i = 0; i < 6; i++)
     {
        printf("%d  %c\n", i, newstr[i] );
     }
    printf ("shalom");
 }

最佳答案

一个简单的方法应该是调用 sprintf()

char newstr[6] = {0};
sprintf(newstr, "%d", value);

在您现有的代码中,str 看起来很简单 {'4', '2', '3', '\0', SomethingRandom, SomethingRandom}。反转它并分配给 newstr 使其成为 {SomethingRandom, SomethingRandom, '\0', '3', '2', '4'},这绝对不是什么你要。事实上,当 str[i] == '\0' 时,您不会分配 newstr,这意味着 newstr[2] == SomethingRandom .

关于c - 将 int 转换为 char 数组的函数,一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27678176/

相关文章:

c++ - 如何填充wav文件的 "data field"

JavaScript 空值检查

Python:为什么 DictWriter 写入 'NULL' 字节?

c - 如何检查 size_t 指针是否为 NULL? (C)

c - Eclipse CDT 火星 : Input from a file

c - 如何仅使用指针比较字符串的单词词典大小 (aba < ada)

c - 为什么我在尝试将 'char (*c)[6]' 传递给需要 'const char (*c)[6]' 的函数时收到警告?

java - 如何从方法返回二维数组索引?

python - 如何在 python 中使用列表/数组理解生成叉积对

c - 我们如何将整个段落作为二维数组中的输入作为单独的行?