c的传值和传址

在c语言中,常常会遇到这样的问题

例子1:

void getMem(int *a)

{

  a = (int *)malloc(sizeof(int));

}

int main()

{

  int *arr, b = 5;

  arr = &b;

  getMem(arr);

  return 0;

}

结果会发现,内存确实申请了,但是arr没有指过去,什么原因呢?

我觉得可以总结一句话:在函数传参数过程中,传过去的变量不可以被改变,改变的只是变量的副本,上述例子中传过去int *a, 实际上还是a,a的值不可改变,在swap(int a, int b)中也是一样的

例子2:

#include <stdio.h>
#include <malloc.h>
typedef struct node
{
  int a;
  struct node *next;
};

void getAddress(node *a)
{
  node *s, *b;
  b = a;
  s = (node *)malloc(sizeof(node));
  s->a = 10;
  s->next = NULL;

  b->next = s;

}
void getAddress1(node *a)
{
  node *s;

  s = (node *)malloc(sizeof(node));
  s->a = 10;
  s->next = NULL;

  a->next = s;
}

void getAddress2(node *a)
{
  a->next = (node *)malloc(sizeof(node));
  a->next->a = 10;
}

void Init(node **a)
{
  *a = (node *)malloc(sizeof(node));
  (*a)->a = 5;
  (*a)->next = NULL;
}

int main()
{
  node *arr;
  Init(&arr);
  printf("arr->next :%p\n", arr->next);
  getAddress3(arr);
  printf("arr->next1 :%p\n", arr->next);
  printf("arr->a: %d \n", arr->a);
  printf("arr->next->a: %d \n", arr->next->a);


  return 0;
}

在这个例子中,在Init(node **a)使用双重指针是因为我们要给main函数中的arr申请空间,让它指向一块申请出来的地址,如果使用单指针的话,就如例子1,它是不能改变arr的值的,a指向的是arr,

已就是a中存的是arr的地址,*a存的才是arr的内容;

至于函数getAddress()和getAddress1()还有getAddress2()的作用是一样的

posted @ 2017-04-25 16:50  独孤流  阅读(227)  评论(0编辑  收藏  举报