SORU
7 Aralık 2008, Pazar


Dönüştürmek için nasıl bir std::string sabit* ya da char*?char

Nasıl char* const char* std::string dönüştürebilir miyim?

CEVAP
7 Aralık 2008, Pazar


Eğer sadece const char* ihtiyacı olan bir fonksiyon için std::string geçmek istiyorsanız kullanabilirsiniz

std::string str;
const char * c = str.c_str();

Eğer yazılabilir bir kopyasını elde etmek istiyorsanız, char * gibi bunu yapabilirsiniz:

std::string str;
char * writable = new char[str.size()   1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

Edit: Yukarıdaki özel durum güvenli değil dikkat edin. Eğer new arayıp delete arama arasında bir şey atar, bir şey sizin için otomatik olarak delete arar gibi bellek sızıntısı olur. Bunu çözmek için iki acil yol vardır.

::scoped_array artırmak

boost::scoped_array kapsam dışına gidiyor üzerine belleği silin

std::string str;
boost::scoped_array<char> writable(new char[str.size()   1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope

::std vektör

Bu standart yöntem (herhangi bir harici kütüphane gerektirmez). Tamamen belleği yöneten std::vector, kullanın.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Best Quality Cartoons

    Best Quality

    10 ŞUBAT 2014
  • LearnCode.academy

    LearnCode.ac

    20 Aralık 2012
  • Wronchi Animation

    Wronchi Anim

    9 Mayıs 2011