c程序单步调试都正确,但是最后出来的结果不正确
程序代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> int getStr(char* source, char* buf1, char* buf2) { /* * 有一个字符串”1a2b3d4z”,; 要求写一个函数实现如下功能, 功能1:把偶数位字符挑选出来,组成一个字符串1。 功能2:把奇数位字符挑选出来,组成一个字符串2。 功能3:把字符串1和字符串2,通过函数参数,传送给main,并打印。 功能4:主函数能测试通过。 * */ char* mySour = source; char myBuf1[] = { 0 };//存放奇数位的字符串 buf1 = myBuf1; char myBuf2[] = { 0 };//存放偶数位的字符串 buf2 = myBuf2; int result = 0; //程序健壮性判断 if(source == NULL || buf1==NULL||buf2==NULL){ printf("source == NULL || buf1==NULL||buf2==NULL"); result = -1; return result; }else{ int len = strlen(mySour);//获取源字符串长度 int i = 0; int j = 0; while(*mySour!='\0'){ *buf1 = *mySour; //printf("==%c\n",*buf1); myBuf1[i] = *buf1; printf("myBuf1[i]=%c\n",myBuf1[i]); buf1++; i++; mySour++; *buf2 = *mySour; //printf("=-=%c\n",*buf2); myBuf2[i-1] = *buf2; printf("myBuf2[i-1]=%c\n",myBuf2[i-1]); buf2++; i++; mySour++; } *buf1 = '\0'; *buf2 = '\0'; buf1 = myBuf1; buf2 = myBuf2; printf("buf1=%s\n",buf1);//输出结果不正确(但是为什么printf("myBuf1[i]=%c\n",myBuf1[i]);这儿是输出结果是正确的) printf("buf2=%s\n",buf2);//输出结果正确 } return result; } void test_getStr(){ char buf[20] = "1a2b3d4z"; char* pb = buf; char odd[]= {0}; char even[]= {0}; char* myOdd = odd; char* myEven = even; int result = getStr(pb,myOdd,myEven); if(result==-1){ printf("失败"); } //printf("奇数位字符串是:%s\n",myOdd); //printf("偶数位字符串是:%s\n",myEven); }
运行结果如下:
myBuf1[i]=1
myBuf2[i-1]=a
myBuf1[i]=2
myBuf2[i-1]=b
myBuf1[i]=3
myBuf2[i-1]=d
myBuf1[i]=4
myBuf2[i-1]=z
buf1=bdz//无论是打印这个指针字符串还是打印输出myBuf1数组都不正确,但是依据运行结果是正确的啊,单步调试的时候运行到buf2++;myBuf1数组的值突然发生变化
buf2=abdz
[ 本帖最后由 轉身已陌路 于 2015-8-21 20:17 编辑 ]