[关闭]
@xxliixin1993 2015-12-12T15:31:04.000000Z 字数 1914 阅读 1393

Program C

C


1. 指针

指针就是储存器中某条数据的地址。

栈 堆 全局量 常量段(只读存储器) 代码段(只读存储器)

每声明一个变量,计算机就会在储存器中某个空间为他创建弓箭。如果在函数中声明变量,计算机就会把它保存在栈(Stack)的储存器区段中如果在函数之外的地方声明变量,计算机则会把它保存在存储器的全局段(Globals)。

  1. int y=1;//全局量段
  2. int main(){
  3. int x=4;//栈 存储器地址例如4100 000, 值为4
  4. return 0;
  5. }

想知道存储器地址,要用&

  1. printf('x的指针是%p', &x);//%p使用来格式化地址的,输出16进制
  2. 输出 0x3E8FA0

&变量 是取这个数据的指针
*指针 是取这个指针的数据
例:

  1. #include <stdio.h>
  2. void goSouthEast(int* lat,int* lon){
  3. *lat=(*lat)--;
  4. *lon=(*lon)--;
  5. }
  6. int main(){
  7. int lat=100;
  8. int lon=10;
  9. goSouthEast(&lat,&lon);
  10. printf("lat:%i\nlon:%i\n", lat,lon);
  11. return 0;
  12. }
  13. [root@www C]# gcc gameShip.c -o gameShip
  14. [root@www C]# ./gameShip
  15. lat:99
  16. lon:10

数组指针

当传字符串的时候,其实传递的是字符串数组指针:

  1. void function_test(char msg[]){
  2. printf("echo %s",msg);
  3. }
  4. char msg[] = "hellow wolrd";
  5. function_test(msg);

注意:

  1. char s[] = "how big is it?";
  2. char *t = s;
  3. sizeof(s);//15
  4. sizeof(t);//32位4,64位8
  5. *s == s[0]
  6. s[i] == *(s+i)

fgets函数
例如:

  1. #include <stdio.h>
  2. int main(){
  3. char sayChar[9];
  4. printf("input\n");
  5. //接收缓存区的指针,接收字符串大小包括\o,stdin表示数据来自键盘
  6. fgets(sayChar,sizeof(sayChar),stdin);
  7. printf("output:%s\n", sayChar);
  8. return 0;
  9. }

注意:如果sayChar是指针就不能用sizeof,要显式指定长度。
例如

char sayChar[]='test';
fgets(sayChar,5,stdin);

2. 字符串

  1. 在C中char s[4]="abc"会被当成字符串数组处理即s={'a','b','c'}
  2. char s[4]只能存1到3个字符,最后一位是结束符\0,这里的4是数组的大小
a b c \0
s[0] s[1] s[2] s[3]

stdio.h这个库里包含标准输入输出的函数
string.h这个库里包含关于字符串的处理的函数

  1. # include <stdio.h>
  2. # include <string.h>
  3. //第一个[]编译器会知道你有3个字符串,所以可以不指定;第二个也可以,但是那样编译器会分配大量的空间,所以这个song数组就占用了3*6=18个字符
  4. char song[][6]={
  5. "qwe",
  6. "asd",
  7. "zxc"
  8. };
  9. void search(char input_string[]){
  10. int i;
  11. for(i=0;i<=2;i++){
  12. if(strstr(song[i],input_string)){
  13. printf("have song %s\n",song[i]);
  14. }
  15. }
  16. }
  17. int main(){
  18. char input_string[6];
  19. printf("input song name\n");
  20. fgets(input_string,sizeof(input_string),stdin);
  21. input_string[strlen(input_string)-1]='\0';
  22. search(input_string);
  23. return 0;
  24. }

注意:
1. 当一个函数要调用另一个函数时,被调用函数一定要写在调用函数之前。
2. strstr() 在字符串里查找字符串
3. strchr() 在字符串里查找字符
4. strcmp() 比较字符串
5. strcpy() 复制字符串
6. strlen() 返回字符串长度
7. strcat() 连接字符串

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注