#include<stdio.h> int isSpecifiedChar(char* p); void swap(char* first, char* end); int Scramble(char* sentence); int Scramble(char* sentence){ int counter = 0; int i = 0; char* headPointer = sentence; int len = strlen(sentence); char* tailPointer = sentence + len -1; char* head = sentence; while(headPointer != tailPointer){ //get the headPointer with specified digit while(!isSpecifiedChar(headPointer)){ if(headPointer == tailPointer){ return counter; } headPointer++; } //get the tailPointer with specified digit while(!isSpecifiedChar(tailPointer)){ if(headPointer == tailPointer){ return counter; } tailPointer--; } if(headPointer == tailPointer){ return counter; } swap(headPointer, tailPointer); counter++; headPointer++; tailPointer--; } return counter; } int isSpecifiedChar(char* p){ if(*p == 33|| (*p >= 36 && *p <= 39) || *p == 44 || *p == 46 || (*p >= 48 && *p <= 59 )|| *p == 63 || (*p>=65 && *p <=90)){ return 1; } return 0; } void swap(char* first, char* end){ char temp; temp = *first; *first = *end; *end = temp; }
许久没有写C语言的代码了,对指针不是很熟悉,导致程序总是出错。同时有一些特性基本都忘光了,导致一个下午都在找bug。
在写的过程中出现了几个错误:
1.在测试的时候在 char* tailPointer = sentence + len -1; 这段代码后面加了一句:printf("%c\n",tailPointer); 输出的结果是Y。如果用int 输出的值是-4195239。结论是未知错误。
2.
最后一段函数
void swap(char* first, char* end){
char temp;
temp =
*first;
*first = *end;
*end = temp;
}
如果定义为char* temp,
*temp = *first;
*first = *end;
*end = *temp
会出现segmentation Fault,原因待查明。
-------------------------------------------------------
结果查明:
每一次定义指针的时候一定要初始化!否则神秘的错误会困扰着你!
在加了temp = first;之后程序又运行起来了,因为声明temp的时候没有初始化导致指向一个随机的位置,所以first无法赋值给temp,导致程序崩溃。