多级指针使用分割字符串
两个赋值指针挖字符串
#include<stdio.h> #include<string.h> #include<stdlib.h> int spitString(const char *buf1,char c,char buf2[10][30],int *count) { char *p = NULL, *pTmp = NULL; int tmpcount = 0; p = buf1; pTmp = buf1; do { p = strchr(p,c); if(p != NULL) { if(p-pTmp > 0) { strncpy(buf2[tmpcount],pTmp,p-pTmp); buf2[tmpcount][p-pTmp] = '\0'; tmpcount++; pTmp = p = p + 1; } } else { break; } }while(*p != '\0'); *count = tmpcount; return 0; } int main() { int iRet = 0, i = 0; char *p1 = "abcdef,acccd,eeee,aaaa,e3eeee,ssss,"; char cTem = ','; int nCount; char myArray[10][30]; iRet = spitString(p1,cTem,myArray,&nCount); if(iRet != 0) { printf("fun spitString() error : %d \n",iRet); } for(i = 0; i < nCount; i++) { printf("%s \n",myArray[i]); } return 0; }
使用第三种内存模型
#include<stdio.h> #include<string.h> #include<stdlib.h> int spitString2(const char *buf1,char c,char **myp,int *count) { char *p = NULL, *pTmp = NULL; int tmpcount = 0; p = buf1; pTmp = buf1; do { p = strchr(p,c); if(p != NULL) { if(p-pTmp > 0) { strncpy(myp[tmpcount],pTmp,p-pTmp); myp[tmpcount][p-pTmp] = '\0'; tmpcount++; pTmp = p = p + 1; } } else { break; } }while(*p != '\0'); *count = tmpcount; return 0; } int main() { int iRet = 0, i = 0; char *p1 = "abcdef,acccd,eeee,aaaa,e3eeee,ssss,"; char cTem = ','; int nCount; char **p = NULL; p = (char **)malloc(10 * sizeof(char *)); if(p == NULL) { return; } for(i = 0; i < 10; i++) { p[i] = (char *)malloc(30 * sizeof(char)); } iRet = spitString2(p1,cTem,p,&nCount); if(iRet != 0) { printf("fun spitString() error : %d \n",iRet); } for(i = 0; i < nCount; i++) { printf("%s \n",p[i]); } for( i = 0; i < 10; i++) { free(p[i]); } free(p); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)