main函数的传参的实现,其实也是一个解析字符串的过程:将每个word后一个空格改为“/0”,将单词提取出来。
就是这么简单。
废话不多说,直接上代码:
1 #include<stdio.h> 2 #include<string.h> 3 void shell_parse(char *sbuf) 4 { 5 char mbuf[50]; 6 sprintf(mbuf,"%s",sbuf); 7 char *buf=mbuf;//两次转换,得到一个能++的指针 8 9 //strcpy(a,buf); 10 int i; 11 int argc=0; 12 char *argv[8]; 13 int state = 0; 14 while(*buf) 15 { 16 char c = *buf; 17 printf("%c\n",c); 18 if(c == ‘ ‘ &&state==0) 19 state = 0; 20 if(c!= ‘ ‘&& state ==0) 21 { 22 argv[argc++] =buf; 23 state = 1; 24 printf("1:::argv[%d]:%s\n",argc,argv[0]); 25 } 26 if(c == ‘ ‘&&state == 1) 27 { 28 *buf = ‘\0‘; 29 state = 0; 30 } 31 /* if(c !=‘ ‘&& state == 0) 32 { 33 argv[argc++] = buf; 34 printf("2::argv[%d]:%s\n",argc,argv[argc]); 35 state = 1; 36 37 }*/ 38 buf++; 39 if(*buf == ‘\n‘) 40 *buf = ‘\0‘; 41 42 } 43 argv[argc] = NULL; 44 45 printf("argc = %d\n",argc); 46 for(i = 0;i<=argc;i++) 47 { 48 printf("argv[%d]:%s\n",i,argv[i]); 49 } 50 // free((void*)buf); 51 } 52 int main(int argc,char **argv) 53 { 54 int i = 0; 55 char buf[64]; 56 //fgets(buf,64,stdin); 57 //printf("buf = %s\n",buf); 58 sprintf(buf,"%s","hsfsfs fsf fsaf;fsa fsfd"); 59 printf("hell"); 60 shell_parse("fsjf sflsdjf dsfsfsdf fs");//此处实现完全传出来的是参数。 61 62 } 63
时间: 2024-12-30 01:04:48