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.阅读递归函数最容易的方法不是纠缠于它的执行过程,而是相信递归函数会顺利完成它的任务。递归函数的变量空间创建于运行时堆栈上。
相关文章推荐
- GDI+中发生一般性错误的解决办法(转帖)
- 剑指offer 两个链表的第一个公共结点
- 多线程下HashMap的死循环问题
- mysql 使用force index优化查询
- 4月份.top域名总量15强:排名大变 易名中国跌至第三
- 递归和迭代区别
- MySQL 批量查询 与 单条多次查询
- 【Spring】Spring MVC原理及配置详解
- define的特殊字符
- Xargs用法详解
- hdu2594Simpsons’ Hidden Talents(kmp)
- Nginx 的 default_server 指令
- Android中用onSaveInstanceState保存Fragment状态的方法
- 蜜罐发展史
- android之绘制相关类
- 为什么不要在category中重写一个类原有的方法
- Unity AssetStore下载目录
- 指针与数组
- 指针数组与数组指针
- C指针陷阱