zoukankan      html  css  js  c++  java
  • C语言中动态分配内存的相关练习

    //有一段文本,将文本中的所有单词存放到一个字符串数组中

    typedef struct _mallocStringArray {
    int strlen;
    char* strAddress;
    } MallocStringArray;
    int getStringSeparateMembersCountsBySymbol(const char* str, const char symbol) {
    if (!str) {
    return (-1);
    }

    typedef enum {
    SYMBOL_FLAG = 0, NONE_FLAG = 1,
    } SymbolFlag;

    char* pSymbol = (char*)str;
    int separateCount = 0;/**< 记录以symbol分离出的元素个数 */
    int flag = NONE_FLAG;

    while (*pSymbol) {
    if (flag == NONE_FLAG && *pSymbol != symbol) {
    separateCount++;
    pSymbol++;
    flag = SYMBOL_FLAG;
    continue;
    }

    if (flag == SYMBOL_FLAG && *pSymbol == symbol) {
    pSymbol++;
    flag = NONE_FLAG;
    continue;
    }

    pSymbol++;
    }

    return (separateCount);
    }

    MallocStringArray* mallocArrayStructToStoreSeparateMembers(const char* str, const char symbol, int* getCount) {
    if (!str) {
    return (NULL);
    }

    /**< 移动到 非'指定字符' 时停止用的指针 */
    char* pLetter = (char*)str;
    /**< 移动到 '指定字符' 时停止用的指针 */
    char* pSymbol = NULL;
    int i = 0;
    /**< 按照 '指定字符' 得到分离的字符串的元素的个数 */
    int count = getStringSeparateMembersCountsBySymbol(str, symbol);
    int tmpCount = count;

    MallocStringArray* pMSA = (MallocStringArray*)malloc(sizeof(MallocStringArray) * count);
    if(!pMSA) {
    return (NULL);
    }

    while (tmpCount--) {
    /**< pLetter移动到 非 '指定字符' 时停止 */
    while (*pLetter == symbol) {
    pLetter++;
    }

    /**< pSymbol移动到 '指定字符' 时停止 */
    pSymbol = pLetter + 1;
    while (*pSymbol != symbol && *pSymbol != '') {
    pSymbol++;
    }

    /**< 完成 malloc 操作以及按照定长拷贝字符串 */
    pMSA[i].strlen = (int)(pSymbol - pLetter);
    pMSA[i].strAddress = (char*)malloc(pSymbol - pLetter + 1);
    if (!pMSA[i].strAddress) {
    return (NULL);
    }
    strncpy(pMSA[i].strAddress, pLetter, pSymbol - pLetter);
    pMSA[i].strAddress[pSymbol - pLetter] = '';

    i++;
    pLetter = pSymbol + 1;
    }

    /**< 返回指针以及数组元素的个数 */
    *getCount = count;
    return (pMSA);

    int main(int argc, const char* argv[]) {

    char* p = "撒旦法 是地方 ds";
    int count = 0;
    MallocStringArray* pMSA = mallocArrayStructToStoreSeparateMembers(p, ' ', &count);

    printf("%d ", count);
    for (int i = 0; i < count; i++) {
    printf("%03d -- %s ", pMSA[i].strlen, pMSA[i].strAddress);
    free(pMSA[i].strAddress);
    }

    free(pMSA);

    return (0);
    }

  • 相关阅读:
    为什么做java开发的公司需要那么多程序员?
    一篇文章了解架构设计的本质
    深入理解 Java 多线程核心知识
    面试经验总结:注意这几点,面试通过率上涨30%
    程序员一般做到多少岁,那些70后的程序员都消失了?
    连阿里都在用它处理亿万级数据统计,论其对Java程序员的重要性!
    【源码】HashMap源码及线程非安全分析
    基于框架的RPC通信技术原理解析
    如何写好一份技术简历?
    彻底理解Netty,这一篇文章就够了
  • 原文地址:https://www.cnblogs.com/yuanyuandachao/p/3337692.html
Copyright © 2011-2022 走看看