??xml version="1.0" encoding="utf-8" standalone="yes"?>国内精品国产成人国产三级粉色,岛国成人av,91精品国产一区二区http://www.aygfsteel.com/shiliqiang/category/40697.htmlI'm on my way!zh-cnSun, 20 Sep 2009 21:07:24 GMTSun, 20 Sep 2009 21:07:24 GMT60对和栈的区别http://www.aygfsteel.com/shiliqiang/articles/295780.html矛_@矛_@Sun, 20 Sep 2009 14:15:00 GMThttp://www.aygfsteel.com/shiliqiang/articles/295780.htmlhttp://www.aygfsteel.com/shiliqiang/comments/295780.htmlhttp://www.aygfsteel.com/shiliqiang/articles/295780.html#Feedback0http://www.aygfsteel.com/shiliqiang/comments/commentRss/295780.htmlhttp://www.aygfsteel.com/shiliqiang/services/trackbacks/295780.html一、预备知识—程序的内存分配

由C/C++~译的程序占用的内存分ؓ以下几个部分
1、栈?stack)Q?q译器自动分配释放 Q存攑և数的参数|局部变量的值等。其操作方式cM于数据结构中的栈?
2、堆?heap)Q?一般由E序员分配释放, 若程序员不释放,E序l束时可能由OS回收。注意它与数据结构中的堆是两回事Q分配方式倒是cM于链表?
3、全局?static)Q?全局变量和静态变量的存储是放在一块的Q初始化的全局变量和静态变量在一块区域, 未初始化的全局变量和未初始化的静态变量在盔R的另一块区域,E序l束后有pȝ释放 ?
4、文字常量区Q?帔R字符串就是放在这里的Q?E序l束后由pȝ释放?
5、程序代码区Q?存放函数体的二进制代码?

Example:

int a = 0; // 全局初始化区
char *p1; // 全局未初始化?
main()
{
int b; // ?
char s[] = "abc"; // ?
char *p2; // ?
char *p3 = "123456"; // 123456\0在常量区Qp3在栈上?
static int c =0Q?// 全局(静?初始化区
p1 = (char *)malloc(10);
p2 = (char *)malloc(20); // 分配得来?0?0字节的区域就在堆区?
strcpy(p1, "123456"); // 123456\0攑֜帔R区,~译器可能会它与p3所指向?123456"优化成一个地斏V?
}


二、堆和栈的理论知?

2.1 甌方式
? ql自动分配?例如Q声明在函数中一个局部变?int b; pȝ自动在栈中ؓb开辟空?
? 需要程序员自己甌Qƈ指明大小Q在c中malloc函数Q如p1 = (char *)malloc(10); 在C++中用newq算W?如p2 = (char *)malloc(10); 但是注意p1、p2本n是在栈中的?

2.2 甌后系l的响应
栈:只要栈的剩余I间大于所甌I间Q系l将为程序提供内存,否则报异常提示栈溢出?
堆:首先应该知道操作pȝ有一个记录空闲内存地址的链表,当系l收到程序的甌Ӟ 会遍历该链表Q寻扄一个空间大于所甌I间的堆l点Q然后将该结点从I闲l点链表中删除,q将该结点的I间分配l程序,另外Q对于大多数pȝQ会在这? 内存I间中的首地址处记录本ơ分配的大小Q这P代码中的delete语句才能正确的释放本内存I间。另外,׃扑ֈ的堆l点的大不一定正好等于申L 大小Q系l会自动的将多余的那部分重新攑օI闲链表中?

2.3 甌大小的限?
栈:在Windows?栈是向低地址扩展的数据结构,是一块连l的内存区域。这句话的意思是栈顶的地址和栈的最大容量是pȝ预先规定好的Q在 WINDOWS下,栈的大小?M(也有的说?MQM是一个编译时q定的常数)Q如果申LI间过栈的剩余I间Ӟ提Coverflow。因 此,能从栈获得的I间较小?
堆:堆是向高地址扩展的数据结构,是不q箋的内存区域。这是由于系l是用链表来存储的空闲内存地址的,自然是不q箋的,而链表的遍历方向是由低地址向高地址。堆的大受限于计算机系l中有效的虚拟内存。由此可见,堆获得的I间比较灉|Q也比较大?

2.4 甌效率的比较:
栈:ql自动分配,速度较快。但E序员是无法控制的?
堆:是由new分配的内存,一般速度比较慢,而且Ҏ产生内存片,不过用v来最方便?
另外Q在WINDOWS下,最好的方式是用VirtualAlloc分配内存Q他不是在堆Q也不是在栈是直接在q程的地址I间中保留一快内存,虽然用v来最不方ѝ但是速度快,也最灉|?

2.5 堆和栈中的存储内?
栈: 在函数调用时Q第一个进栈的是主函数中后的下一条指?函数调用语句的下一条可执行语句)的地址Q然后是函数的各个参敎ͼ在大多数的C~译器中Q参数是? 叛_左入栈的Q然后是函数中的局部变量。注意静态变量是不入栈的。当本次函数调用l束后,局部变量先出栈Q然后是参数Q最后栈指针指向最开始存的地址Q? 也就是主函数中的下一条指令,E序p点l运行?
堆:一般是在堆的头部用一个字节存攑֠的大。堆中的具体内容有程序员安排?

2.6 存取效率的比?
char s1[] = "aaaaaaaaaaaaaaa";
char *s2 = "bbbbbbbbbbbbbbbbb";
aaaaaaaaaaa是在q行时刻赋值的Q?
而bbbbbbbbbbb是在~译时就定的;
但是Q在以后的存取中Q在栈上的数l比指针所指向的字W串(例如?快?
比如Q?
#include
void main()
{
char a = 1;
char c[] = "1234567890";
char *p ="1234567890";
a = c[1];
a = p[1];
return;
}
对应的汇~代?
10: a = c[1];
00401067 8A 4D F1 mov cl,byte ptr [ebp-0Fh]
0040106A 88 4D FC mov byte ptr [ebp-4],cl
11: a = p[1];
0040106D 8B 55 EC mov edx,dword ptr [ebp-14h]
00401070 8A 42 01 mov al,byte ptr [edx+1]
00401073 88 45 FC mov byte ptr [ebp-4],al
W一U在d时直接就把字W串中的元素d寄存器cl中,而第二种则要先把指针D到edx中,在根据edxd字符Q显然慢了?

2.7 结Q?
堆和栈的区别可以用如下的比喻来看出: 使用栈就象我们去饭馆里吃饭,只管点菜(发出甌)、付钱、和?使用)Q吃׃pQ不必理会切菜、洗菜等准备工作和洗、刷锅等扫尾工作Q他的好处是 快捷Q但是自由度?使用堆就象是自己动手做喜Ƣ吃的菜_比较ȝQ但是比较符合自q口味Q而且自由度大?

q有是函数调用时会在栈上有一pd的保留现场及传递参数的操作。栈的空间大有限定QVC的缺省是2M。栈不够用的情况一般是E序中分配了大量数组和? 归函数层ơ太深。有一点必ȝ道,当一个函数调用完q回后它会释放该函数中所有的栈空间。栈是由~译器自动管理的Q不用你操心。堆是动态分配内存的Qƈ? 你可以分配用很大的内存。但是用不好会生内存泄漏。ƈ且频J地malloc和free会生内存碎?有点cM盘片)Q因为C分配动态内存时是寻 扑֌配的内存的。而用栈则不会产生片。在栈上存取数据比通过指针在堆上存取数据快些。一般大家说的堆栈和栈是一LQ就是栈(stack)Q而说堆时? 是堆heap。栈是先入后出的Q一般是由高地址向低地址生长?br />

摘自Qhttp://linux.chinaunix.net/bbs/thread-1119653-1-1.html


矛_@ 2009-09-20 22:15 发表评论
]]>
能测试你c语言功底的几个问?/title><link>http://www.aygfsteel.com/shiliqiang/articles/291970.html</link><dc:creator>矛_@</dc:creator><author>矛_@</author><pubDate>Thu, 20 Aug 2009 08:24:00 GMT</pubDate><guid>http://www.aygfsteel.com/shiliqiang/articles/291970.html</guid><wfw:comment>http://www.aygfsteel.com/shiliqiang/comments/291970.html</wfw:comment><comments>http://www.aygfsteel.com/shiliqiang/articles/291970.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/shiliqiang/comments/commentRss/291970.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/shiliqiang/services/trackbacks/291970.html</trackback:ping><description><![CDATA[下面有几个简单测试将能发C对C语言的掌握情c?br /> int x=35;<br /> char str[10];<br /> //问:strlen(str)和sizeof(str)的值分别是多少Q?br /> strcpy(str,"www.it315.org"/*?3个字?/);<br /> //?此时x和strlen(str)的值分别是多少Q?br /> str="it315.org";//~译能通过吗?<br /> char *pstr;<br /> strcpy(pstr,"http://www.it315.org");<br /> //上句~译能通过吗?q行时有问题吗?<br /> const char *p1;<br /> char * const p2;<br /> //上面两句有什么区别吗Q?br /> p1=(const char *)str;<br /> //如果是p1=strQ编译能够通过吗?明白Z么要cd转换Q类型{换的本质是什么?<br /> strcpy(p1,"abc");//~译能够通过吗?<br /> printf("%d",str);//有问题吗Q?br /> pstr=3000;//~译能过吗?如果不行Q该如何修改以保证编译通过呢?<br /> long y=(long)pstr;//可以q样做吗Q?br /> int *p=str;<br /> *p=0x00313200;<br /> printf("%s",str);//会是什么效果?提示0x31对应字符'1',0x32对应字符'2'?br /> p=3000;//p+1的结果会是多?<br /> char *pc=new char[100];//上述语句在内存中占据几个内存块,怎样的布局情况Q?br /> void test(char **p)<br /> {<br />        *p=new char[100];<br /> }//q个~译函数有问题吗Q外面要调用q个函数Q该怎样传递参敎ͼ<br /> //能明白typedef int (*PFUN)(int x,int y)及其作用吗?<br /> <br /> <br /> 摘自Qhttp://blog.csdn.net/zhangxiaoxiang/archive/2006/05/17/742931.aspx<br /> <img src ="http://www.aygfsteel.com/shiliqiang/aggbug/291970.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/shiliqiang/" target="_blank">矛_@</a> 2009-08-20 16:24 <a href="http://www.aygfsteel.com/shiliqiang/articles/291970.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>void cd的指?/title><link>http://www.aygfsteel.com/shiliqiang/articles/290353.html</link><dc:creator>矛_@</dc:creator><author>矛_@</author><pubDate>Sat, 08 Aug 2009 09:09:00 GMT</pubDate><guid>http://www.aygfsteel.com/shiliqiang/articles/290353.html</guid><wfw:comment>http://www.aygfsteel.com/shiliqiang/comments/290353.html</wfw:comment><comments>http://www.aygfsteel.com/shiliqiang/articles/290353.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/shiliqiang/comments/commentRss/290353.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/shiliqiang/services/trackbacks/290353.html</trackback:ping><description><![CDATA[<div id="wmqeeuq" class="posttitle"> <a id="viewpost1_TitleUrl" class="singleposttitle" >void指针</a> </div> 指针有两个属?指向变量/对象?font style="line-height: 1.3em;" color="#ff0000">地址</font> <div id="wmqeeuq" class="singlepost"><wbr>?font style="line-height: 1.3em;" color="#ff0000">长度</font><wbr> <br /> 但是指针只存储地址,长度则取决于指针的类?<br /> ~译器根据指针的cd从指针指向的地址向后d <br /> 指针cd不同则寻址范围也不?比如: <br /> int*从指定地址向后L4字节作ؓ变量的存储单?<br /> double*从指定地址向后L8字节作ؓ变量的存储单?<br /> <br /> 1.void指针是一U特别的指针 <br />    void *vp <br />   //说它特别是因为它没有cd <br />   //或者说q个cd不能判断出指向对象的长度 <br /> <br /> 2.M指针都可以赋值给void指针 <br />   type *p; <br />   vp=p; <br />   //不需转换 <br />   //只获得变?对象地址而不获得大小 <br /> <br /> 3.void指针赋值给其他cd的指针时都要q行转换 <br />    type *p=(type*)vp; <br />    //转换cd也就是获得指向变?对象大小 <br /> ?http://icoding.spaces.live.com/blog/cns!209684E38D520BA6!130.entry <br /> <br /> 4.void指针不能复引?<br />   *vp//错误 <br />   因ؓvoid指针只知?指向变量/对象的v始地址 <br />   而不知道指向变量/对象的大?占几个字?所以无法正引?<br /> <br /> 5.void指针不能参与指针q算,除非q行转换 <br />    (type*)vp++; <br />   //vp==vp+sizeof(type)<br /> <br /> <br /> <br /> #include<iostream><br /> #include<stdlib.h><br /> #include<string><br /> using namespace std;<br /> typedef struct tag_st <br /> { <br /> char id[10];<br /> float fa[2];<br /> }ST; <br /> //我在E序里面q样使用?<br /> int main()<br /> {<br /> ST * P=(ST *)malloc(sizeof(ST));<br /> strcpy(P->id,"hello!");<br /> P->fa[0]=1.1;<br /> P->fa[1]=2.1;<br /> <br /> ST * Q=(ST *)malloc(sizeof(ST));<br /> strcpy(Q->id,"world!");<br /> Q->fa[0]=3.1;<br /> Q->fa[1]=4.1;<br /> void ** plink=(void **)P;<br /> *((ST *)(plink)) = * Q; //<font style="line-height: 1.3em;" color="#ff0000">plink要先强制转换一?目的是ؓ了让它先知道要覆盖的大小.</font><wbr><br />                          //<font style="line-height: 1.3em;" color="#ff0000">P的内容竟然给Q的内容覆盖掉?</font><wbr><br /> cout<<P->id<<" "<<P->fa[0]<<" "<<P->fa[1]<<endl;<br /> return 0;<br /> }<br /> <br /> <br /> <br /> 转自Qhttp://www.cppblog.com/dragon/archive/2008/09/02/60760.aspx<br /> </div> <img src ="http://www.aygfsteel.com/shiliqiang/aggbug/290353.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/shiliqiang/" target="_blank">矛_@</a> 2009-08-08 17:09 <a href="http://www.aygfsteel.com/shiliqiang/articles/290353.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>指针详解http://www.aygfsteel.com/shiliqiang/articles/285866.html矛_@矛_@Tue, 07 Jul 2009 13:21:00 GMThttp://www.aygfsteel.com/shiliqiang/articles/285866.htmlhttp://www.aygfsteel.com/shiliqiang/comments/285866.htmlhttp://www.aygfsteel.com/shiliqiang/articles/285866.html#Feedback0http://www.aygfsteel.com/shiliqiang/comments/commentRss/285866.htmlhttp://www.aygfsteel.com/shiliqiang/services/trackbacks/285866.html
The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte). These single-byte memory cells are numbered in a consecutive way, so as, within any block of memory, every cell has the same number as the previous one plus one.

This way, each cell can be easily located in the memory because it has a unique address and all the memory cells follow a successive pattern. For example, if we are looking for cell 1776 we know that it is going to be right between cells 1775 and 1777, exactly one thousand cells after 776 and exactly one thousand cells before cell 2776.

Reference operator (&)

As soon as we declare a variable, the amount of memory needed is assigned for it at a specific location in memory (its memory address). We generally do not actively decide the exact location of the variable within the panel of cells that we have imagined the memory to be - Fortunately, that is a task automatically performed by the operating system during runtime. However, in some cases we may be interested in knowing the address where our variable is being stored during runtime in order to operate with relative positions to it.

The address that locates a variable within memory is what we call a reference to that variable. This reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator, and which can be literally translated as "address of". For example:

ted = &andy;


This would assign to ted the address of variable andy, since when preceding the name of the variable andy with the reference operator (&) we are no longer talking about the content of the variable itself, but about its reference (i.e., its address in memory).

From now on we are going to assume that andy is placed during runtime in the memory address 1776. This number (1776) is just an arbitrary assumption we are inventing right now in order to help clarify some concepts in this tutorial, but in reality, we cannot know before runtime the real value the address of a variable will have in memory.

Consider the following code fragment:

andy = 25;
fred = andy;
ted = &andy;


The values contained in each variable after the execution of this, are shown in the following diagram:



First, we have assigned the value 25 to andy (a variable whose address in memory we have assumed to be 1776).

The second statement copied to fred the content of variable andy (which is 25). This is a standard assignment operation, as we have done so many times before.

Finally, the third statement copies to ted not the value contained in andy but a reference to it (i.e., its address, which we have assumed to be 1776). The reason is that in this third assignment operation we have preceded the identifier andy with the reference operator (&), so we were no longer referring to the value of andy but to its reference (its address in memory).

The variable that stores the reference to another variable (like ted in the previous example) is what we call a pointer. Pointers are a very powerful feature of the C++ language that has many uses in advanced programming. Farther ahead, we will see how this type of variable is used and declared.

Dereference operator (*)



We have just seen that a variable which stores a reference to another variable is called a pointer. Pointers are said to "point to" the variable whose reference they store.

Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by".

Therefore, following with the values of the previous example, if we write:

beth = *ted;


(that we could read as: "beth equal to value pointed by ted") beth would take the value 25, since ted is 1776, and the value pointed by 1776 is 25.



You must clearly differentiate that the expression ted refers to the value 1776, while *ted (with an asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25. Notice the difference of including or not including the dereference operator (I have included an explanatory commentary of how each of these two expressions could be read):

beth = ted;   // beth equal to ted ( 1776 )
beth = *ted; // beth equal to value pointed by ted ( 25 )


Notice the difference between the reference and dereference operators:
  • & is the reference operator and can be read as "address of"
  • * is the dereference operator and can be read as "value pointed by"
Thus, they have complementary (or opposite) meanings. A variable referenced with & can be dereferenced with *.

Earlier we performed the following two assignment operations:

andy = 25;
ted = &andy;


Right after these two statements, all of the following expressions would give true as result:

andy == 25
&andy == 1776
ted == 1776
*ted == 25


The first expression is quite clear considering that the assignment operation performed on andy was andy=25. The second one uses the reference operator (&), which returns the address of variable andy, which we assumed it to have a value of 1776. The third one is somewhat obvious since the second expression was true and the assignment operation performed on ted was ted=&andy. The fourth expression uses the dereference operator (*) that, as we have just seen, can be read as "value pointed by", and the value pointed by ted is indeed 25.

So, after all that, you may also infer that for as long as the address pointed by ted remains unchanged the following expression will also be true:

*ted == andy


Declaring variables of pointer types

Due to the ability of a pointer to directly refer to the value that it points to, it becomes necessary to specify in its declaration which data type a pointer is going to point to. It is not the same thing to point to a char as to point to an int or a float.

The declaration of pointers follows this format:

type * name;


where type is the data type of the value that the pointer is intended to point to. This type is not the type of the pointer itself! but the type of the data the pointer points to. For example:

int * number;
char * character;
float * greatnumber;


These are three declarations of pointers. Each one is intended to point to a different data type, but in fact all of them are pointers and all of them will occupy the same amount of space in memory (the size in memory of a pointer depends on the platform where the code is going to run). Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an int, the second one to a char and the last one to a float. Therefore, although these three example variables are all of them pointers which occupy the same size in memory, they are said to have different types: int*, char* and float* respectively, depending on the type they point to.

I want to emphasize that the asterisk sign (*) that we use when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator that we have seen a bit earlier, but which is also written with an asterisk (*). They are simply two different things represented with the same sign.

Now have a look at this code:

// my first pointer
#include <iostream>
using namespace std;

int main ()
{
int firstvalue, secondvalue;
int * mypointer;

mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
firstvalue is 10
secondvalue is 20


Notice that even though we have never directly set a value to either firstvalue or secondvalue, both end up with a value set indirectly through the use of mypointer. This is the procedure:

First, we have assigned as value of mypointer a reference to firstvalue using the reference operator (&). And then we have assigned the value 10 to the memory location pointed by mypointer, that because at this moment is pointing to the memory location of firstvalue, this in fact modifies the value of firstvalue.

In order to demonstrate that a pointer may take several different values during the same program I have repeated the process with secondvalue and that same pointer, mypointer.

Here is an example a little bit more elaborated:

// more pointers
#include <iostream>
using namespace std;

int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20

cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
firstvalue is 10
secondvalue is 20


I have included as a comment on each line how the code can be read: ampersand (&) as "address of" and asterisk (*) as "value pointed by".

Notice that there are expressions with pointers p1 and p2, both with and without dereference operator (*). The meaning of an expression using the dereference operator (*) is very different from one that does not: When this operator precedes the pointer name, the expression refers to the value being pointed, while when a pointer name appears without this operator, it refers to the value of the pointer itself (i.e. the address of what the pointer is pointing to).

Another thing that may call your attention is the line:

int * p1, * p2;


This declares the two pointers used in the previous example. But notice that there is an asterisk (*) for each pointer, in order for both to have type int* (pointer to int).

Otherwise, the type for the second variable declared in that line would have been int (and not int*) because of precedence relationships. If we had written:

int * p1, p2;


p1 would indeed have int* type, but p2 would have type int (spaces do not matter at all for this purpose). This is due to operator precedence rules. But anyway, simply remembering that you have to put one asterisk per pointer is enough for most pointer users.

Pointers and arrays

The concept of array is very much bound to the one of pointer. In fact, the identifier of an array is equivalent to the address of its first element, as a pointer is equivalent to the address of the first element that it points to, so in fact they are the same concept. For example, supposing these two declarations:

int numbers [20];
int * p;


The following assignment operation would be valid:

p = numbers; 


After that, p and numbers would be equivalent and would have the same properties. The only difference is that we could change the value of pointer p by another one, whereas numbers will always point to the first of the 20 elements of type int with which it was defined. Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an array can be considered a constant pointer. Therefore, the following allocation would not be valid:

numbers = p;


Because numbers is an array, so it operates as a constant pointer, and we cannot assign values to constants.

Due to the characteristics of variables, all expressions that include pointers in the following example are perfectly valid:

// more pointers
#include <iostream>
using namespace std;

int main ()
{
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
return 0;
}
10, 20, 30, 40, 50, 


In the chapter about arrays we used brackets ([]) several times in order to specify the index of an element of the array to which we wanted to refer. Well, these bracket sign operators [] are also a dereference operator known as offset operator. They dereference the variable they follow just as * does, but they also add the number between brackets to the address being dereferenced. For example:

a[5] = 0;       // a [offset of 5] = 0
*(a+5) = 0; // pointed by (a+5) = 0


These two expressions are equivalent and valid both if a is a pointer or if a is an array.

Pointer initialization

When declaring pointers we may want to explicitly specify which variable we want them to point to:

int number;
int *tommy = &number;


The behavior of this code is equivalent to:

int number;
int *tommy;
tommy = &number;


When a pointer initialization takes place we are always assigning the reference value to where the pointer points (tommy), never the value being pointed (*tommy). You must consider that at the moment of declaring a pointer, the asterisk (*) indicates only that it is a pointer, it is not the dereference operator (although both use the same sign: *). Remember, they are two different functions of one sign. Thus, we must take care not to confuse the previous code with:

int number;
int *tommy;
*tommy = &number;


that is incorrect, and anyway would not have much sense in this case if you think about it.

As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is declared:

char * terry = "hello"; 


In this case, memory space is reserved to contain "hello" and then a pointer to the first character of this memory block is assigned to terry. If we imagine that "hello" is stored at the memory locations that start at addresses 1702, we can represent the previous declaration as:



It is important to indicate that terry contains the value 1702, and not 'h' nor "hello", although 1702 indeed is the address of both of these.

The pointer terry points to a sequence of characters and can be read as if it was an array (remember that an array is just like a constant pointer). For example, we can access the fifth element of the array with any of these two expression:

*(terry+4)
terry[4]


Both expressions have a value of 'o' (the fifth element of the array).

Pointer arithmetics



To conduct arithmetical operations on pointers is a little different than to conduct them on regular integer data types. To begin with, only addition and subtraction operations are allowed to be conducted with them, the others make no sense in the world of pointers. But both addition and subtraction have a different behavior with pointers according to the size of the data type to which they point.

When we saw the different fundamental data types, we saw that some occupy more or less space than others in the memory. For example, let's assume that in a given compiler for a specific machine, char takes 1 byte, short takes 2 bytes and long takes 4.

Suppose that we define three pointers in this compiler:

char *mychar;
short *myshort;
long *mylong;


and that we know that they point to memory locations 1000, 2000 and 3000 respectively.

So if we write:

mychar++;
myshort++;
mylong++;


mychar, as you may expect, would contain the value 1001. But not so obviously, myshort would contain the value 2002, and mylong would contain 3004, even though they have each been increased only once. The reason is that when adding one to a pointer we are making it to point to the following element of the same type with which it has been defined, and therefore the size in bytes of the type pointed is added to the pointer.



This is applicable both when adding and subtracting any number to a pointer. It would happen exactly the same if we write:

mychar = mychar + 1;
myshort = myshort + 1;
mylong = mylong + 1;


Both the increase (++) and decrease (--) operators have greater operator precedence than the dereference operator (*), but both have a special behavior when used as suffix (the expression is evaluated with the value it had before being increased). Therefore, the following expression may lead to confusion:

*p++


Because ++ has greater precedence than *, this expression is equivalent to *(p++). Therefore, what it does is to increase the value of p (so it now points to the next element), but because ++ is used as postfix the whole expression is evaluated as the value pointed by the original reference (the address the pointer pointed to before being increased).

Notice the difference with:

(*p)++

Here, the expression would have been evaluated as the value pointed by p increased by one. The value of p (the pointer itself) would not be modified (what is being modified is what it is being pointed to by this pointer).

If we write:

*p++ = *q++; 


Because ++ has a higher precedence than *, both p and q are increased, but because both increase operators (++) are used as postfix and not prefix, the value assigned to *p is *q before both p and q are increased. And then both are increased. It would be roughly equivalent to:

*p = *q;
++p;
++q;


Like always, I recommend you to use parentheses () in order to avoid unexpected results and to give more legibility to the code.

Pointers to pointers

C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or even to other pointers). In order to do that, we only need to add an asterisk (*) for each level of reference in their declarations:

char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;


This, supposing the randomly chosen memory locations for each variable of 7230, 8092 and 10502, could be represented as:



The value of each variable is written inside each cell; under the cells are their respective addresses in memory.

The new thing in this example is variable c, which can be used in three different levels of indirection, each one of them would correspond to a different value:

  • c has type char** and a value of 8092
  • *c has type char* and a value of 7230
  • **c has type char and a value of 'z'


void pointers

The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).

This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.

One of its uses may be to pass generic parameters to a function:

// increaser
#include <iostream>
using namespace std;

void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{ char* pchar; pchar=(char*)data; ++(*pchar); }
else if (psize == sizeof(int) )
{ int* pint; pint=(int*)data; ++(*pint); }
}

int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}
y, 1603


sizeof is an operator integrated in the C++ language that returns the size in bytes of its parameter. For non-dynamic data types this value is a constant. Therefore, for example, sizeof(char) is 1, because char type is one byte long.

Null pointer

A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type.

int * p;
p = 0; // p has a null pointer value


Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere", while a void pointer is a special type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer itself and the other to the type of data it points to.

Pointers to functions

C++ allows operations with pointers to functions. The typical use of this is for passing a function as an argument to another function, since these cannot be passed dereferenced. In order to declare a pointer to a function we have to declare it like the prototype of the function except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name:

// pointer to functions
#include <iostream>
using namespace std;

int addition (int a, int b)
{ return (a+b); }

int subtraction (int a, int b)
{ return (a-b); }

int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}

int main ()
{
int m,n;
int (*minus)(int,int) = subtraction;

m = operation (7, 5, addition);
n = operation (20, m, minus);
cout <<n;
return 0;
}
8


In the example, minus is a pointer to a function that has two parameters of type int. It is immediately assigned to point to the function subtraction, all in a single line:

int (* minus)(int,int) = subtraction;

 



矛_@ 2009-07-07 21:21 发表评论
]]>
վ֩ģ壺 Ӣ| | ʡ| | Ȫ| Ӧ| | | | °| | | | | Դ| | ˮ| | ˳| Ͼ| ͼľ| ˹| ϰ| ɽ| | | ½| ƽ| | ľ| | ۶| | ĩ| | | | ˮ| | ϳ| Դ|