Char * string and the difference between C ++

Char * string and the difference between C ++

 

1. Definition:

string: string among STL is a container, its packaging, it is very easy to operate.

char *: char * is a pointer can point to a string array, as the array can be allocated on the stack, you may also be necessary to manually release allocated on the heap, piled words.

2, the difference between:

string of memory management is handled by the system, unless the system memory pool is used up, or will not happen memory problems.
char * Memory management is handled by the users themselves, it is prone to memory shortage.

When we want to save a string, but do not know how much memory other needs, with string to handle better and better.
When you know the storage memory, you can use char *, but not as good as with a string of good, there will always be a pointer
risks.

A string member function may also be used to process a variety of each character string to facilitate processing.
Deal with char * string, not as good string of convenience, there is no corresponding function to be called directly, but to compile their own
write function to finish processing strings, and with the process pointer still prone to memory problems.

char * s = "string" content is not changed; char s [10] = "string" content can be changed

3, attention:

When we define a string, you can not use scanf ( "% s", s) and printf ( "% s", s) input and output. Mainly because the first address% s is required behind the object

4, the conversion:

When the string directly into const char *, two functions can c_str (), data member function, for example:

Copy the code
#include <the iostream> 
#include <stdio.h> 
the using namespace STD; 
int main () 
{ 
    String S = "Xiaoming"; 
    const char * A = s.c_str (); // compilation errors will remove const 
    const char * s.data = B (); 
    the printf ( "A: [S%], B: [% S] \ n-", A, B); 
}
Copy the code

If the direct conversion of char * is also available. But I think this is very troublesome.

Will be converted to char * string, can be directly converted. Note that the output of the problem:

Copy the code
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char *a="xiaoming";
    string s;
    s=a;
    printf("%s\n",s.c_str());
}
Copy the code

 

 

Guess you like

Origin www.cnblogs.com/tsingke/p/12075078.html