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);
}

原文地址:https://www.cnblogs.com/yuanyuandachao/p/3337692.html