zoukankan      html  css  js  c++  java
  • 指针(二)

    1、指向数组的指针

    例子:

    int a[]={'a','b','c'};

    int *p=a;

    则*(p+i) 等价于a[i]

    亲,注意不要越界噢,尤其是处理字符窜的时候,注意\0!!

    2、指针数组

    还是一个数组,只不过数组元素是指针了

    例子:

    char *argv[]就非常典型

    3、指针与字符窜

    处理字符窜的时候要主意\0这个小子

    例子:

     /*                                                                                                           
      2  *功能:自己实现strcmp函数
      3  *心得:记住要入口检测;另外要注意程序的版式,即代码风格
      4  * */
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 /*strcmp:
      8  * if s<t return<0
      9  * if s==t return=0
     10  * if s>t return>0*/
     11 /*int strcmp(char *s,char *t)
     12 {
     13     int i;
     14     for (i = 0; s[i] == t[i]; i++)
     15         if (s[i] == '\0')
     16             return 0;
     17     return s[i] - t[i];
     18 }*/
     19 /*strcmp:指针实现*/
     20 int my_strcmp(char *s,char *t)
     21 {
     22     for ( ; *s == *t;s++,t++)
     23         if (*s == '\0')
     24             return 0;
     25     return *s - *t;
     26 }
    
    27 int main()
     28 {
     29     char *s = "abcd";
     30     char *t = "abedc";
     31     printf("%d\n",my_strcmp(s,t));//返回-2
     32     return 0;
     33 }

    4、指针与函数

    在我看来,只有中国人需要搞清楚这两哥们的区别,语言问题,呵呵。

    1、指针函数:注意哦,本质上是函数,只不过它的返回值类型是一个指针

    例子:今天翻看自己原来写的数据结构程序,碰见了,就补充到这里

    typedef int ELEM;
    
    struct ListNode
    {
    	ELEM data;
    	ListNode* link;
    };
    
    typedef ListNode* ListPtr;
    
    
    
    //生成一个含有n个节点的链表,头节点不存放数据
    ListPtr	CreateList(void)
    {
    	int i,n=0;
    	ListPtr head,last;
    	ListPtr p1,p2;
    	printf("请输入您要创建的链表的数目:\n");
    	scanf("%d",&n);
    	head=p1=p2 = (ListPtr)malloc(sizeof(struct ListNode));
    	for(i=1;i<=n;i++)
    	{
    		p2 = (ListPtr)malloc(sizeof(struct ListNode));
    		p1->link = p2;
    		printf("请输入第%d个节点的数据:\n",i);
    		scanf("%d",&(p2->data));
    		p1 = p2;	
    	}
    	last = p1;
    	last->link  =NULL;
    	return head;
    }


    2、函数指针:注意哦,本质上是指针,只不过它指向了一个函数的首地址,即该指针的值是一个函数的入口地址

    例子:昨天写得太着急,没有认真举例子,今天反省一番,决定努力一把,争取以后每个知识点都附上一个可以运行的例子,才能做到栩栩如生,哈哈

    #include <stdio.h>
    #include <STDLIB.H>
    /*完成两数相加,并返回*/
    int fun(int a,int b)
    {
    	return a+b;
    }
    
    int main()
    {
    	//定义一个函数指针
    	int (*pf)(int,int) = fun;
    	//
    	int ans = 0;
    	ans = fun(2,2);//普通
    	ans = (*pf)(2,2);//函数指针使用1
    	ans = pf(2,2);//函数指针使用2
    	printf("%d\n",ans);
    	return 0;
    }




    评注:因为总结得比较急忙,准备过几天在编写更经典的代码时,再修改这些日志,到时候会把例子的链接加上就好了吐舌头

  • 相关阅读:
    windows 创建python独立开发环境
    sql多列排序
    mysql 导入sql脚本中文乱码问题
    廖雪峰Python教学课后作业---datetime
    poj 1004:Financial Management(水题,求平均数)
    【POJ水题完成表】
    poj 1003:Hangover(水题,数学模拟)
    ytu 2558: 游起来吧!超妹!(水题,趣味数学题)
    poj 1005:I Think I Need a Houseboat(水题,模拟)
    hdu 2393:Higher Math(计算几何,水题)
  • 原文地址:https://www.cnblogs.com/javaadu/p/11742717.html
Copyright © 2011-2022 走看看