Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

c++ - C ++:初学者有关数组和指针的问题(C++: Questions about array and pointer from a beginner)

I am new to C++ and to programming in general.

(我是C ++和一般编程人员的新手。)

I got confused when I learnt the concepts of pointer and array.

(当我学习了指针和数组的概念时,我感到困惑。)

Takes int*p = arr; int arr[]={5,1};

(取int*p = arr; int arr[]={5,1};) int*p = arr; int arr[]={5,1}; as an example.

(举个例子。)

I learnt that arr is also a pointer.

(我了解到arr也是一个指针。)

                                p(a pointer)                          arr[0]
the thing it stores:    [first element address: 601]                   [5]
its memory         :                501                                601
address(just make 
some fake address)

However,                                 arr(the pointer)
                                  [first element address: 601]
                                               601

Normally, a pointer should have a different address from the array.

(通常,指针应具有与数组不同的地址。)

However, the arr , as the pointer to the first element, has the same address as the first element.

(但是,作为指向第一个元素的指针的arr具有与第一个元素相同的地址。)

So I feel confused.

(所以我感到困惑。)

And I wonder whether it is because the memory box of arr[0] is split into two parts: one part for arr[0] , and one part for the pointer arr , so that they have the same address in memory.

(而且我想知道是否是因为arr[0]的存储盒分为两部分: arr[0]一部分和指针arr一部分,以便它们在内存中具有相同的地址。)

  ask by 汝風留名 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest that pointers are not a beginner topic in C++, they are mostly just a carry over from C. If you can, you should avoid them and use the STL Containers .

(我建议指针不是C ++中的新手话题,它们大多只是C的遗留物。如果可以的话,应避免使用它们并使用STL容器 。)


In your code sample, the type of arr is int[2] .

(在您的代码示例中, arr的类型为int[2] 。)

You should think of that in memory as looking something like this:

(您应该在内存中将其视为如下所示:)

arr --+
      |
      v
    +---+---+
    | 5 | 1 |
    +---+---+

The value contained in arr is the location of the first element (the 5 ).

(arr包含的值是第一个元素( 5 )的位置。)

arr is essentially a pointer to that 5 .

(arr本质上是指向5的指针。)

The only difference being that the type ( int[2] ) has also remembered how many elements there are.

(唯一的区别是类型( int[2] )还记住了有多少个元素。)

The assignment statement p = arr works because p 's type is int* which int[] can decay to.

(赋值语句p = arr起作用是因为p的类型是int* ,而int[]可以归为int* 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...