[C#]变量、指针、地址、指针的指针.........

      编程资料 2004-12-19 18:36
变量、指针、地址、指针的指针.........

最近看到关于论坛中关于指针和地址,有很多帖子。这里也来谈谈,相信阅后能彻底明白什么是指针,这是学习C及其其衍生语言的第一道难关!!
应具备的基础知识: 二进制(及其相关进制)及其如何表示各种各样的东西如整数、浮点数、字符等,计算机CPU基本工作原理,内存是什么、用来干什么, 类型、变量是什么,什么是operator(操作符、操作码、算子、运算符...) 和Operands(操作数、操作域、运算域、运算对象、运算数....)

这里使用一个小程序来弄明白什么是指针及其使用

using System;

namespace pot
{
class pointer123
{
public struct myIntstruct 结构是什么? 数组是什么? 在C#中,基本类型boolintflot等也都是结构(类的一种,原来语言中结构含义有扩展)
{
public int int1;
public int int2;
public int int3;
public myIntstruct(int i1, int i2, int i3)
{
int1 = i1;
int2 = i2;
int3 = i3;
}
}struct myIntstruct end
unsafe static void Main(string[] args)
{
myIntstruct myintstructV = new myIntstruct(2, 4, 6);
int intptr1 = null;
intptr1 = (int ) &myintstructV ;
理解指针、数组、数组下标、内存与地址及其关系
Console.WriteLine(n use like array -----n);
for (int i=0; i3; i++)
{
Console.WriteLine(intptr1[{0}] {1}, i,intptr1[i]);
}
理解指针、指针运算(这里使用了增量,?增了什么)、内存与地址及其关系
Console.WriteLine(n use pointer, step by step -----n);
for (int i=0; i3; i++)
{
Console.WriteLine(intptr1+{0} {1},i, intptr1 );
intptr1++;
}
理解指针、结构及其成员变量的获得
Console.WriteLine(n use . to get struct member -----n);
myIntstruct myintstructP = null;
myintstructP = &myintstructV;
Console.WriteLine((myintstructP).int1 {0}, (myintstructP).int1 );
Console.WriteLine((myintstructP).int2 {0}, (myintstructP).int2 );
Console.WriteLine((myintstructP).int3 {0}, (myintstructP).int3 );
Console.WriteLine(n use - to get struct member -----n);
Console.WriteLine(myintstructP-int1 {0}, myintstructP-int1 );
Console.WriteLine(myintstructP-int2 {0}, myintstructP-int2 );
Console.WriteLine(myintstructP-int3 {0}, myintstructP-int3 );
现在看指针、指针的指针、指针的指针的指针(如果你愿意还可以指针下去^_^)、内存与地址及其关系
int temp = 5;
int intP = null;
int intPP = null;
int intPPP = null;
intP = &temp;
intPP = &intP;
intPPP = &intPP;
Console.WriteLine(n use pointer to pointer to pointer -----n);
Console.WriteLine( temp {0}n, temp);
Console.WriteLine( intP1 {0}n, intP);
Console.WriteLine( intPP {0}n, intPP);
Console.WriteLine(intPPP {0}n, intPPP);
Console.WriteLine(Now,All OK! Bye!);
Console.ReadLine();
}
}class pointer123 end
}

这是一个C#程序,你可以使用notepad编辑它,存为pot.cs文件,在命令行使用 csc unsafe pot.cs 编译就得到pot.exe,执行即可!(csc是.Net FrameWork SDK的C#程序编译器)
若你使用VS.NET环境,就建立C#项目-控制台应用程序,用上述代码替换文件内容,修改编译条件-允许unsafe模式,即可编译运行!!

运行结果:
------------------------
use like array -----
intptr1[0] 2
intptr1[1] 4
intptr1[2] 6
use pointer, step by step -----
intptr1+0 2
intptr1+1 4
intptr1+2 6
use . to get struct member -----
(myintstructP).int1 2
(myintstructP).int2 4
(myintstructP).int3 6
use - to get struct member -----
myintstructP-int1 2
myintstructP-int2 4
myintstructP-int3 6
use pointer to pointer to pointer -----
temp 5
intP1 5
intPP 5
intPPP 5
Now,All OK! Bye!
标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}