您的位置:首页 > 其它

C和指针之学习笔记(2)

2016-04-27 10:15 197 查看

第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_char’ from 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章 函数

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

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.阅读递归函数最容易的方法不是纠缠于它的执行过程,而是相信递归函数会顺利完成它的任务。递归函数的变量空间创建于运行时堆栈上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: