C指针

先看下下面代码:
#include "stdio.h"
#include "conio.h"

void go_south_east(int lat, int lon){
lat = lat -1;
lon = lon + 1;
}

int main()
{
int latitude = 32;
int longitude = -64;
go_south_east(latitude, longitude);
printf("Avast! Now at: [%i, %i]\n", latitude, longitude);

getch();
return 0;

}


结果并不是31, -63,而是32, -64

并没有改变,这个时候必须要知道C语言中的指针的概念,而且这个概念是必须应该掌握的

int main()
{
int x = 8;
int z=18;
printf("x is %i and the address is %p\n", x, &x);

x= z;
printf("x is %i and the address is %p\n", x, &x);

return 0;
}

结果为:

[img]http://dl2.iteye.com/upload/attachment/0097/5857/06a39358-cee1-3c66-8a8d-6facdc9654f2.jpg[/img]

[b]%p是输出地址格式,&x是指x的内存地址[/b]

回到第一个程序中,当main方法中调用go_south_east()方法的时候,两个参数都是传递值,那么实际上lat,lon被赋值了,并且进行了加减操作,而main方法中的latitude,longitude 两个参数地址不会变,值也没有变。

[b]1,获取变量的存储地址,即变量的指针 用&x
2,指针变量是用来存储指针的变量 比如 int * address_x = &x;
3,获取指针变量所指向的值 int y = *address_x;
改变其值就用*address_x=9,即 x=9[/b]


所以第一个程序应该写成
#include "stdio.h"
#include "conio.h"

void go_south_east(int * lat, int * lon){


*lat = *lat -1;
*lon = *lon + 1;

}

int main()
{
int latitude = 32;
int longitude = -64;
go_south_east(&latitude, &longitude);
printf("Avast! Now at: [%i, %i]\n", latitude, longitude);

getch();
return 0;

}

[b]
关键点:
Variables are allocated storage in memory.
Local variables live in the stack.
Global variables live in the globals section.
Pointers are just variables that store memory addresses.
The & operator finds the address of a variable.
The * operator can read the contents of a memory address.
The * operator can also set the contents of a memory address.[/b]

你可能感兴趣的:(C语言)