Categories

Follow Me …

JoeNo1 @ YouTube
JoeNo1 @ Twitter JoeNo1 @ FaceBook
JoeNo1 @ YouKu.COM JoeNo1 @ TuDou.COM
JoeNo1 @ 56.COM JoeNo1 @ 6.CN

Similarity of Arrays and Pointers in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* Similarity of Arrays and Pointers in C++
. similar usage of array and pointer variables
. use pointer arithmatic to access array[i]
. use pt[i] for pointer as using an array
*/

#include <iostream>;
using namespace std;
int main(int argc, char *argv[])
{
int a[3];
for (int i=0; i<2; i++)
    *(a+i)=i+10;            // use array as pointer: a[i] = i+10;
    cout<< *a << endl       // use array as pointer: a[0]
        << *(a+1) << endl   // a[1] // *(a++)   does NOT work
        << *(&amp;*a+2) << endl;    // a[2] // *(&amp;(*a)+2)   // out of bound
    int b=100;
    int* pt=&b;
    for (int i=0; i<2; i++)
        *(pt+i)=i+900;          // use pointer as array
        for (int i=0; i&lt;2; i++)
            cout<< pt[i] << endl;       // use pointer as array
    // an other point: No new, but delete
    delete [] a;                    // only get a warning
    cout<< "\n\n" << a[1] << endl;      // does NOT delete the content
system("PAUSE");
return EXIT_SUCCESS;
}
/* output
10
11
2088809675              // out of bound
900
901
11
*/
Share

No related posts.

4 comments to Similarity of Arrays and Pointers in C++

  • 老兄专业IT/业余Guitar?
    或是相反?。。。交流交流

  • 路人甲

    呵呵,从youtube摸过来看你的吉他的,顺便发现了c++的东西,给你的代码提点意见
    第17行没有out of bound,而是第13行的循环条件错了
    绝对不要写21-24行这样的东西
    27行,delete一定只能用在new出来的东西上,第28行也一样,这几行都可能引起runtime error
    而且28行注释是不对的,delete做了什么取决于类型的析构函数和编译器,运行环境的实现

    另外pointer和array的问题,pointer和array是不同的类型,“arrays are pointers”是不对的,之所以有这种误解是因为 1.c++有array到pointer的默认转型,2.如果有函数形参(parameters)是array的和形参是相对应的pointer的函数,重载解析是会认为是同一个函数。
    也就是说,如果没有转型,那么这是两类不同的类型,没有转型的情况包括:模板实参,sizeof操作数以及其他不涉及函数调用的地方。

    • 感谢详细的解说,我受益匪浅。这段程序是我学习C++时自己写的测试。在网上搜索了一下,才知道函数“形参”是指“pass-by-value”,函数“实参”是指“pass-by-reference”。。。

      Joe

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>