在C中将int转换为char [英] Converting an int to a char in C

查看:98
本文介绍了在C中将int转换为char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

char* intToString(int N);
int power(int N, int M)
{   
    int n = N;
    if (M ==0) return 1;
    int i;
    for( i = 1; i < M; i++)
        N*=n;
    return N;
}

int main()
{
   printf("%s",intToString(100));
}

char* intToString(int N)
{   
   float M = N;
   int numberLen = 1;
   while(M > 1) 
   { 
      M /= 10;numberLen++;
   }
   int ar[numberLen];
   char str[numberLen + 1];
   int i;
   for(i = 0; i < numberLen; i++)
   {
      str[numberLen - i - 1] = (N%power(10,i+1))/(power(10,i));
   }
   str[numberLen] = '\0';
   return str; 
}

我正在尝试解决C语言中的Euler项目问题​​。这里有一个小问题,当我运行该程序时,我得到一个带有一些数字的正方形,与字符串 100相对。

I am trying to solve the Euler project problems in C. I have run into a little issue here, when I run this program I get a square with some numbers in it as oppose to a string "100".

推荐答案

在您的代码中,

 char str[numberLen + 1];

str 对于您的函数 intToString

如果尝试返回指向该数组的指针并尝试使用调用程序函数中的返回值,它将调用未定义的行为,因为当函数完成执行时,数组不再存在,并且返回的指针变为无效。尝试使用无效的内存会调用UB。

If you try to return a pointer to this array and try to make use of the return value in the caller function, it will invoke undefined behavior as when the function finishes execution, the array cease to exist and the returned pointer renders invalid. Attempt to make use of invalid memory invokes UB.

您可以使 str 成为指针并使用动态内存分配功能像 malloc() 或家族分配内存。在那种情况下,即使函数完成执行,分配的内存的生命周期仍然有效,直到 free() -d显式使用返回值不是错误。

You can make str a pointer and use dynamic memory allocation functions like malloc() or family to allocate memory to that. In that case, even if the function finishes execution, the lifetime of the allocated memory remains valid until free()-d explicitly and making use of the return value is not an error.

这篇关于在C中将int转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆