使用itoa()的最佳做法是什么

she*_*ngy 0 c++ memory-leaks memory-management itoa

当我使用itoa()它需要一个char*_DstBuff,这里最好的做法是什么?

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
  int num = 100;

  // I'm sure here is no memory leak, but it needs to know the length.
  char a[10]; 

  // will this causue memory leak? if yes, how to avoid it?
  // And why can itoa(num, b, 10); be excuted correctly since b
  // has only allocated one char.
  char *b = new char; 

  // What is the difference between char *c and char *b
  // both can be used correctly in the itoa() function
  char *c = new char[10]; 

  itoa(num, a, 10);
  itoa(num, b, 10);
  itoa(num, c, 10);

  cout << a << endl;
  cout << b << endl;
  cout << c << endl;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出为:100 100 100

所以有人能解释这里char *b = new char;char *c = new char[10];这里之间的区别吗?

我知道char *c会动态分配10个字符,但这意味着char *b只会动态分配1个字符,如果我对此正确,为什么输出都正确?

实际上哪个是a,b或c的最佳实践?

Ker*_* SB 6

最佳实践:根本不要使用它.

为什么?因为它不符合标准.

我该怎么做呢?使用std::to_string.

(如果你真的不得不使用itoa,那么使用一个大的本地静态缓冲区,就像char[512]那样 - 如果你真的非常安全,你可以制作数组大小sizeof(unsigned long long int) * CHAR_BIT + 2或类似的东西,所以它总是可以保持任何数字表示在任何基地,加号.)

  • @shengy,一个altenative是得到一个体面的编译器:-)热潮,谢谢,我整个星期都在这里. (2认同)
  • VC6,哇.考虑升级到现代编译器?从长远来看,这将为您节省大量工作. (2认同)