简体   繁体   English

在C中将int转换为char

[英]Converting an int to a char in C

#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; 
}

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". 我正在尝试解决C语言中的Euler项目问题​​。我在这里遇到了一个小问题,当我运行该程序时,我得到一个带有一些数字的正方形,与字符串“ 100”相对。

In your code, 在您的代码中

 char str[numberLen + 1];

str is local to your function intToString . str是函数intToString局部intToString

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. 尝试使用无效的内存会调用UB。

You can make str a pointer and use dynamic memory allocation functions like malloc() or family to allocate memory to that. 您可以使str成为指针,并使用malloc()或family之类的动态内存分配函数来为其分配内存。 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. 在那种情况下,即使函数完成执行,分配的内存的生命周期也将保持有效,直到显式地使用free() d并且使用返回值都不是错误。

In addition to the solution suggested by the other answer , you can pass an array of char from main to intToString . 除了其他答案建议的解决方案之外,您还可以将一个char数组从main传递给intToString That will avoid the need to use dynamic memory allocation. 这将避免使用动态内存分配的需要。

char* intToString(int N, char* buffer);

...

int main()
{
   char buffer[20]; // Make it large enough for your need.
   printf("%s",intToString(100, buffer));
}

char* intToString(int N, char* buffer)
{
   // Replace use of str by buffer

   ...

   return buffer;
}

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

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