【发布时间】:2012-01-10 03:51:14
【问题描述】:
当我使用 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 的最佳实践是哪个?
【问题讨论】:
-
在编写 C++ 时为什么要使用
itoa? -
@Cody:因为
itoa比标准库中的其他实用程序更强大(支持许多不同的基础)并且效率更高。 -
鉴于没有人提到它...
#include <stdlib.h>long int strtol(const char *nptr, char **endptr, int base);long long int strtoll(const char *nptr, char **endptr, int base);
标签: c++ memory-leaks memory-management itoa