C achieve string string

String String implemented in C, using the string defined as typedef char *.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef char* string;

string get_string(string);

int main(void)
{
    string name = get_string("What's your name?\n");
    printf("Hello, %s!\n", name);
    printf("strlen: %d\n", strlen(name));

    return 0;
}

string get_string(stringMSG) 
{ 
    int len = . 8 ;
     String STR = ( String ) the malloc ( the sizeof ( char ) * len);   // dynamic allocation of length len of the string pointer 
    char * ptr = STR;   // to by ptr pointer to STR 
    char CH;
     int I = 0 ; 

    the printf ( " % S " , MSG);
     the while (! (CH = getchar ()) = ' \ n- ' )   // cycle received byte, until the user enters a carriage return 
    {
         * PTR ++ = CH ;   //The assigned to ch * ptr ptr points to a next address and 
        I ++ ;
         IF (I == len)   // If full length 
        {
             String tmp = STR;   // tmp point STR 
            len * = 2 ;   // length double 
            str = ( string ) the malloc ( the sizeof ( char ) * len);   // STR redirect a doubled dynamic allocation length string pointer 
            strcpy (STR, tmp);   // the tmp characters are copied to the STR     
            PTR = STR + i;   // ptr now points to a new str of the i-th character address 
            as Free (tmp);   // release the memory space
            = tmp NULL; 
        } 
    }
     * PTR = ' \ 0 ' ;   // string pointer must be the last character '\ 0' 

    return STR; 
}

Guess you like

Origin www.cnblogs.com/noonjuan/p/12054464.html