重新温故C语言发现好多基本的东西在大学期间没有深刻理解,导致基础太差,特别是指针,想起来觉得满可悲的,大学时虽然也努力学习了,可惜啊,深度不够,现在在linux下重学C语言,收获颇多。
如今工作多年,重新回顾那段岁月,思海起伏,如若重新来过,我愿意终日与你为伴。
题目:用C语言指针实现字符串的反转,比如输入“ABCD”,输出“DCBA”;
要求:不能使用数组下标,不能使用C库函数中任何跟字符串操作相关的函数,不能声明用一个字符数组来临时存放字符串。
代码如下:
#include <stdio.h>#include <string.h>
void reverse_string(char *string)
{
char temp_pch = '\0';
char *pstr = string;
int len=0;
int i = 0;
if(*string == '\0')
{
printf("The string is null.\n");
}
else
{
while(*string++ != '\0')
len++; /*取字符串长度*/
pstr = string-2; /*取完长度后,指针指向字符串末尾的结束字符位置,需要移动到末尾一个有效字符上。*/
string = string-len-1; /*指针重新移到字符串头部*/
for(i=0; i<len/2; i++)
{
temp_pch = *string;
*string = *pstr;
*pstr = temp_pch;
string++; /*字符串头尾互换,指针移动到中间即完成头尾互换*/
pstr--;
}
printf("The string were reversed is: %s\n", string);
}
}
main()
{
char orig_str[] = "Happy New Year, my dear friend!"; /*只能定义成数组,不能是指针。*/
reverse_string(orig_str);
}
linux上编译通过。
注:main ()中 orig_str定义的时候不能定义成char *orig_str = "Happy New Year, my dear friend!"。如果定义成指针形式,则指针指向一个字符串常量,存放在内存中的只读存储区,在GCC编译的时候,reverse_string()函数中头尾互换时,*string = *pstr会报段错误,因为*string和*pstr指针指向的这段内存是只读的,现在要改变他们的值,违背了指针操作内存的原则,所以会报段错误。
《The C programming language》第二版,5.5章94页有如下一段话:
char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */
amessage is an array, just big enough to hold the sequence of characters and '\0' that
initializes it. Individual characters within the array may be changed but amessage will always
refer to the same storage. On the other hand, pmessage is a pointer, initialized to point to a
string constant; the pointer may subsequently be modified to point elsewhere, but the result is
undefined if you try to modify the string contents.