64,639
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <cstring>
int main()
{
// C-style character string implementation
const char *pc = "a very long literal string";
const size_t len = strlen(pc +1); // space to allocate
std::cout<<len<<std::endl;
// performance test on string allocation and copy
int i=0;
for (size_t ix = 0; ix != 10; ++ix,++i)
{
char *pc2 = new char[len + 1]; // allocate the space
strcpy(pc2, pc); // do the copy
if (strcmp(pc2, pc)) // use the new string
; // do nothing
std::cout<<pc2<<std::endl;
std::cout<<i<<std::endl;
delete [] pc2; // free the memory
}
system("pause");
return 0;
}
#include <stdafx.h>
#include <iostream>
#include <cstring>
int main()
{
// C-style character string implementation
const char *pc = "a very long literal string";
const size_t len = strlen(pc); //注意把这里改成这样,因为你后面new的时候len+1了
std::cout<<len<<std::endl;
// performance test on string allocation and copy
int i=0;
for (size_t ix = 0; ix != 10; ++ix,++i)
{
char *pc2 = new char[len + 1]; // allocate the space
strcpy(pc2, pc); // do the copy
if (strcmp(pc2, pc)) // use the new string
; // do nothing
std::cout<<pc2<<std::endl;
std::cout<<i<<std::endl;
delete [] pc2; // free the memory
}
//system("pause");
return 0;
}