当我使用 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;
}
输出为:100 100 100
char *b = new char;
那么有人能解释一下和这里的区别char *c = new char[10];
吗?
我知道char *c
会动态分配 10 个字符,但这意味着char *b
只会动态分配 1 个字符,如果我是对的,为什么输出都是正确的?
实际上,哪个是 a、b 或 c 的最佳实践?