开发者

What is the value of a dereferenced pointer

I realized that I had some confusion regarding the value of a dereferenced pointer, as I was reading a C text with the following code snippet:

int main() 
{ 
    int matrix[3][10];                 // line 3: matrix is tentatively defined
    int (* arrPtr)[10] = matrix;       // line 4: arrPtr is defined and initialize
    (*arrPtr)[0] = 5;                  // line 5: what is the value 开发者_C百科of (*arrPtr) ?

My confusion is in regards to the value of *arrPtr in the last line. This is my understanding upto that point.

Line 3, matrix is declard (tentatively defined) to be an array of 3 elements of type array of 10 elements of type int.

Line 4, arrPtr is defined as a pointer to an array of 10 elements of type int. It is also initialized as a ptr to an array of 10 elements (i.e. the first row of matrix)

Now Line 5, arrPtr is dereferenced, yielding the actual array, so it's type is array of 10 ints.

MY question: Why is the value of the array, just the address of the array and not in someway related to it's elements?


The value of the array variable matrix is the array, however it (easily) "degrades" into a pointer to its first item, which you then assign to arrPtr.

To see this, use &matrix (has type int (*)[3][10]) or sizeof matrix (equals sizeof(int) * 3 * 10).

Additionally, there's nothing tentative about that definition.

Edit: I missed the question hiding in the code comments: *arrPtr is an object of type int[10], so when you use [0] on it, you get the first item, to which you then assign 5.

Pointers and arrays are purposefully defined to behave similiarly, and this is sometimes confusing (before you learn the various quirks), but also extremely versatile and useful.


I think you need to clarify your question. If you mean what is the value of printf("%i", arrPtr); then it will be the address of the array. If you mean printf("$i",(*arrPtr)[0] ); then we've got a more meaty question.


In C, arrays are pretty much just a convenience thing. All an “array” variable is is a pointer to the start of a block of data; just as an int [] equates to an int*, i.e. the location in memory of an int, an int [][] is a double pointer, an int**, which points to the location in memory of... another pointer, which in turn points to an actual particular int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜