c++学习(五):new char[]的赋值

    xiaoxiao2021-12-14  19

    1.strcpy

            string str = "mystring"; int num = strlen(str.c_str()) +1; char* strchar = new char[num];        strcpy(strchar, str.c_str()); if (strchar!=NULL) { delete []strchar; strchar = NULL; }

    2.memcpy

            string str = "mystring";

    int num = strlen(str.c_str()) +1;

    char* strchar1 = new char[num]; memcpy(strchar1, str.c_str(), num); if (strchar1!=NULL) { delete []strchar1; strchar1 = NULL; }

    3.不能直接赋值为字符串常量。这样的话,char 的地址发生变化, delete crash.

    char* strchar2 = new char[num]; strchar2 = "mystring";///wrong

    转载请注明原文地址: https://ju.6miu.com/read-969024.html

    最新回复(0)