不定行长二维数组(字符串数组)

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*有一串字符串char* str="This,is,a,test,"
1.以逗号分隔字符,形成二维数组(字符串数组),并传出来: arr={"This","is","a","test"};
2.把二维数组的行数也传出来
*/

int strToArr(char* str,char*** arr,int* num){
	char* pos = NULL;
	char* pos2 = NULL;
	char** tmp=NULL;
	int row_len = 0;
	int col_len=0;
	int i=0;

	pos = strstr(str,",");
	while(pos){//第一次遍历求行数
		row_len++;
		pos++;
		pos=strstr(pos,",");
	}
	*num = row_len;
	tmp = (char**)malloc(row_len*sizeof(char*));

	pos = str;
	pos2= strstr(pos,",");
	while (pos2)//第二次遍历,求每一列长度
	{
		col_len = pos2-pos;
		tmp[i]=(char*)malloc((col_len+1)*sizeof(char));//注意多分配一个'\0'
		memcpy(tmp[i],pos,col_len);
		tmp[i][col_len]='\0';
		i++;
		pos = ++pos2;
		pos2 = strstr(pos,",");
	}
	*arr = tmp;

	return 0;
}

void main() {
	char str[]="This,is,a,test,";//结尾必须是逗号
	char** arr;
	int num = 0;
	strToArr(str,&arr,&num);

	for(int i=0;i<num;i++){
		puts(arr[i]);
	}
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/itswrj/article/details/88366580