#include <stdio.h>
#include "string.h"
#include "stdlib.h"
///自己封裝的拷貝字符串的方法
int ericCopy(char *to,char *from,long num){
int ret = 0;
if (from == NULL||to==NULL||num ==0) {
return -1;
}
for (int i = 0; strlen(from); i++) {
if (i<num) {
to[i] = from[i];
}else{
to[i] = '\0';
break;
}
}
return ret;
}
int spitString(char *string,char spit,char **buff,int *count){
int ret = 0;
int temCount =0;
if (string ==NULL||buff==NULL||count==NULL) {
return -1;
}
char *p = string;
char *ptmp = string;//臨時指針
do {
p = strchr(ptmp, spit);
if (p == NULL) {
ret = -2;
break;
}
//strncpy(buff[temCount], p, p-ptmp);
ericCopy(buff[temCount], ptmp, p-ptmp);
buff[temCount][p-ptmp] = '\0';
// printf("%s",buff[temCount]);
temCount++;
ptmp = p = p+1;
} while (*p!='\0');
*count = temCount;
return ret;
}
void freeMemory(char **p,int num){
if (p == NULL) {
return;
}
for (int i = 0; i<num; i++) {
free(p[i]);
}
p = NULL;//把實參賦值成NULL
}
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
// char **buff = {"adf","ewr","asgaggd","wtew","dsgdsag"};
char *buff = "adfadf,sdggd,sdf,erer,erer,";
int count = -1;
// char array[10][30];
char **array = NULL;//這里使用動態分配內存的方法
array = (char**)malloc(10*sizeof(char *));
for (int i = 0; i<10; i++) {
array[i] = (char *)malloc(30*sizeof(char));
}
printf("%s",array[2]);
spitString(buff, ',', array, &count);
printf("%p",array);
if (count!=0) {
for (int i = 0; i<count; i++) {
printf("\n%s",array[i]);
}
printf("\n");
}
//free(array);
freeMemory(array, count);//釋放內存
return 0;
}
一個練習分割字符串,二級指針分配內存
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
- 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
推薦閱讀更多精彩內容
- 今天遇到一個C語言實現判斷任意大小矩陣(二維數組)是否為單位矩陣的題目,要求第一個參數為整型指針,第二個參數為矩陣...
- JavaScript split() 方法 定義和用法split() 方法用于把一個字符串分割成字符串數組。 語法...