简体   繁体   中英

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".

In your code,

 char str[numberLen + 1];

str is local to your function 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.

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.

In addition to the solution suggested by the other answer , you can pass an array of char from main to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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