重拾C,一天一点点_10

来博客园今天刚好两年了,两年前开始学编程。

忙碌近两个月,项目昨天上线了,真心不容易,也不敢懈怠,接下来的问题会更多。这两天调试服务器,遇到不少麻烦。

刚出去溜达了一下,晚上天凉了,现在手感觉凉的有点不灵活了都。大伙多注意身体!

继续我的C。发现个问题,自己的文章排版很丑,以后也要多注意。

printf(“hello world”);

printf接受的是一个指向字符数组第一个字符的指针。也就是说,字符串常量可通过一个指向其第一个元素的指针访问。

char *p;

p = “hello world”;   //将一个指向字符串数组的指针赋值给p。该过程没有进行字符串的复制,只是涉及到指针的操作。C语言没有提供将整个字符串作为一个整体进行处理的运算符。

char s[] = “hello world”;  //定义一个字符数组

char *p = “hello world”;  //定义一个指针

两种声明的区别:

s是一个仅足以存放初始化字符串及空字符’\0’的一维数组,数组中的单个字符可以修改。

p始终指向同一个存储位置,其初始值指向一个字符串常量,之后它可以被修改以指向其他地址,如果试图修改字符串的内容,结果是没有定义的。

//复制字符串

1 #include <stdio.h> 2 void strcpy1(char *s, char *t); 3 4 main(){ ; 6char s[] = “”; 7 strcpy1(s,t); ,s); }strcpy1(char *s, char *t){12int i = 0;){14i++;15 }16 }

1 #include <stdio.h> 2 void strcpy2(char *s, char *t); 3 4 main(){ ; 6char s[] = “”; 7 strcpy2(s,t); ,s); }strcpy2(char *s, char *t){){13s++;14t++;15 }16/**17 //简写 18 while((*s++=*t++) != ‘\0’)19 ;*22 //再简写 23 while(*s++=*t++)24 ;}

刚遇到这个警告:conflicting types for built-in function ‘strcpy’

  函数命名冲突了

//比较两字符串

1 #include <stdio.h> 2 int strcmp(char *s, char *t); 3 4 main(){ ;;,strcmp(s,t));}strcmp(char *s, char *t){11int i;12for(i=0; s[i]==t[i]; i++){){;15 }16 }17return s[i] – t[i];18 }

#include <stdio.h>int strcmp(char *s, char *t);main(){ char t[] = “hello world”;char s[] = “helloabc”;printf(“%d\n”,strcmp(s,t));//65}/****比较两字符串顺序***/int strcmp(char *s, char *t){for(; *s==*t; s++,t++) {if(*s == ‘\0’){return 0;}}return *s – *t;}

一个函数实现或一种算法的实现,还是需要用数据去模拟,然后找出规律。就上例,作简单分析:

s1 “hello world”;

s2 “helloabc”;

for循环,i=0,s[0]=t[0],依此类推,s[4]=t[4],当i=5时,s[5]是一个空格,t[5]=a,s[5]!=t[5],跳出for循环,返回a字符与空格字符的差,97-32=65。假如t[5]也是一个空格的话,继续下一个比较,如果s[6]==‘\0’的话,说明s[5]还是等于t[5],返回0。

以后尽量都要去多分析原理,加深记忆。

指针数组及指向指针的指针

  指针本身也是变量,所以它也可以其他变量一样存储在数组中。

二维数组

今天是2013年的第300天,今年只剩65天,大家多多珍惜吧!很巧的是,,之前的测试中字符a-空格刚好也是65。

1 #include <stdio.h> 2 int day_of_year(int year, int month, int day); 3 void month_day(int year, int yearday, int *pmonth, int *pday);daytab[2][13] = { 6{0,31,28,31,30,31,30,31,31,30,31,30,31}, 7{0,31,29,31,30,31,30,31,31,30,31,30,31} 8 }; 9 main(){, day_of_year(pmonth = 0;12int pday = 0;13int year = 2013;14int yearday = 300;15month_day(year, yearday, &pmonth, &pday);,year, yearday,pmonth,pday);;18 }day_of_year(int year, int month, int day){21int i, leap;22leap = (year%4 == 0 && year%100 != 0) || (year %400 == 0);23for(i=1; i<month; i++){24day += daytab[leap][i];25 }26return day;27 }month_day(int year, int yearday, int *pmonth, int *pday){30int i, leap;31leap = (year%4 == 0 && year%100 != 0) || (year %400 == 0);32for(i=1; yearday>daytab[leap][i]; i++){33yearday -= daytab[leap][i];34 }35*pmonth = i;36*pday = yearday;37 }

附:

不要等待机会,而要创造机会。

重拾C,一天一点点_10

相关文章:

你感兴趣的文章:

标签云: