6章 指针

1.在一组字符串中查找字符:

#include<stdio.h>

#include<assert.h>

#include<stdlib.h>

 

#define TRUE 1

#define FALSE 0

 

int find_char(char **strings , int value)

{

//  assert(strings != NULL);

 

  while(*strings !=NULL){

        while(**strings!='\0'){

           if(*(*strings)++ == value )

                {

                puts("i can be here!\n");

                return TRUE;

                }

}

  strings++;

}

return FALSE;

}

int main()

{

 char abc[5][5]={"abcd","efgh","ijkl","mnop"};

 char **p;

 p=(char **)malloc(sizeof(char**));   //需要注意1

 *p=&abc[0][0];

 char value;

 puts("Please input your char:");

 scanf("%c",&value);

 

 int num=find_char(p,value);     // 需要注意

 printf("number is %d\n",num);

 

 return 0;

}

 

(1)声明了指针之后要对其进行初始化,因为指针变量不会自动分配任何内存。否则会出现错误:Segmentation fault (core dumped)

(2)二数组名代表了数组的起始地址,如 char arr[5][6]; 那么数组名 arr就是这个二维数组的首地址。这样的写法:char arr[5][6], *p; p=arr;是错误的,二维数组名是一个二级指针,是地址的地址  ,char arr[5][6]; char **p; p=arr;这样写同样是错误的

     直接将abc传给find_char是错误的,即:find_char(abc,value)。这样会出现错误:passing argument 1 of find_charfrom incompatible pointer type

 

2.字符串反向打印

#include<stdio.h>

#include<stdlib.h>

 

void reverse_string(char *string)

{

 char *p;

 p=(char *)malloc(sizeof(char *));

 p=string;

 while(*p!='\0'){    //只能用*p!='\0’作为判断条件,不能用p!=NULL,此时p指向了’\0’

  p++;

}

 printf("The reverse string is : ");

 while(p>=string){  //这里的条件很重要

 putchar(*p);

 p--;

}

printf("\n");

}

 

int main()

{

char abc[20];

puts("Please input your string:");

scanf("%s",abc);

printf("the string is : %s\n",abc);

reverse_string(abc);

return 0;

}

 

7章 函数

  1. 规则:所有参数都是传值调用数组例外,因为数组参数的值是一个指针,下标引用实际上是对这个指针执行间接访问操作。

eg:整数交换

void  swap(int x, int y)

{

   int  temp;

   temp = x;

   x = y;

   y = temp;

}

   无效,因为实际交换的是参数的拷贝,原先的参数值并未进行交换。

 

void  swap(int *x, int *y)   //有效

{

   int  temp;

   temp = *x;

   *x = *y;

   *y = temp;

}

 

2.‘0’+0=’0’;  ‘0’+1=’1’;  ‘0’+2=’2’;  .......

 

3.阅读递归函数最容易的方法不是纠缠于它的执行过程,而是相信递归函数会顺利完成它的任务。递归函数的变量空间创建于运行时堆栈上。

 

posted on 2016-04-27 10:15  绽放的四叶草  阅读(230)  评论(0编辑  收藏  举报