Question

Question about array and pointer?

So, I have this array and pointer:

char array [6];

char *ptr;

And this list of array [6] addresses and contents:

0x5010 a

0x5011 b

0x5012 F

0x5013 H

0x5014 X

0x5015 Y

How do I initialize ( C assignment statement) the pointer and ptr to make it point to the first element of the array?

Also, how do I find out what the values of the following statements are: &array[0], array[0], *ptr , and (*ptr)+2 .

Can someone explain this to me, please?

Answers

Hi,

First, a little terminology:

* An array is a contiguous block of memory, where all elements have the same type and size.

* A pointer is a variable in memory that points to something (or contains its address).

In C, we have two operators to deal with pointers:

* The asterisk (e.g., *a) will dereference a pointer. In other words *a is the object to which a points at. If a points at an array, *a will be the first element of the array.

* The ampersand (e.g., &a) yields a pointer to object a. If a is an int, &a will be a pointer to int, also called an int *.

There's just one more thing you need to know. When declaring an array, its base name can be used as a pointer to the array (in other words, a pointer to the beginning of the array: a pointer to the first element). So if you have int a[10]; You can use either &a[0] or a to express the same thing.

Lets look at your expressions:

&array[0] == a pointer to the first element. The same as just saying array.

array[0] == the first element of the array.

*ptr == the object to which ptr points at. If you initially did ptr = array; then *ptr would be array[0]. To achieve the same effect, you can also write ptr = &array[0].

(*ptr) + 2 == The same as above but you add 2 to the resulting value. Same as saying array[0] + 2. However, the parantheses are not needed because the * operator binds more tightly than the + operator (it has higher precedence).

*(ptr + 2) == The same as saying &array[2].

I hope that helped.

Cheers,

Bogdan

#1