注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 CCNA教材推荐
 帮助

C:指针与函数


2007-12-06 16:22:49
 标签:函数 C 指针   [推送到技术圈]

版权声明:原创作品,如需转载,请与作者联系。否则将追究法律责任。
1.指针作为形参
void exchange(int * const ptr1,int * const ptr2)
{
   
int temp;

    temp=*ptr1;
    *ptr1=*ptr2;
    *ptr2=temp;
}

void do_exchange()
{
   
int i1=100,i2=200,*p1=&i1,*p2=&i2;

    printf(
"i1=%i,i2=%i\n",i1,i2);
    exchange(p1,p2);
    printf(
"i1=%i,i2=%i\n",i1,i2);
    exchange(&i1,&i2);
    printf(
"i1=%i,i2=%i\n",i1,i2);
}

2.从函数返回一个指针
struct linkedlist
{
   
int value;
   
struct linkedlist *next;
};
struct linkedlist *head;

struct linkedlist *create()
{
   
struct linkedlist n1,n2,n3;

    n1.value=1;
    n2.value=2;
    n3.value=3;
    n1.next=&n2;
    n2.next=&n3;
    n3.next=NULL;
    head=&n1;
   
return head;
}

struct linkedlist *find (struct linkedlist *listPtr,int target)
{
   
while(listPtr!=NULL)
     
if(listPtr->value==target)
       
return listPtr;
     
else
        listPtr=listPtr->next;
   
return NULL;
}

void do_find()
{
   
struct linkedlist *plist;
   
int search;
    create();

    printf(
"Enter value to locate: ");
    scanf(
"%i",&search);

    plist=find(head,search);
   
if(plist!=NULL)
      printf(
"Found %i\n",plist->value);
   
else
      printf(
"Not found\n");
}

struct linkedlist *create();//返回一个结构体linkedlist指针
struct linkedlist *find (struct linkedlist *listPtr,int target);//返回一个结构体linkedlist指针

本文出自 “子 孑” 博客,转载请与作者联系!



上一篇 C:关键字const与指针  下一篇 C:宏定义



    文章评论
 
2007-12-06 17:56:44
不错 写的真详细呀

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: