create a pointer, initialize it to the beginning of the array data |
p = &data[0];
That's one way of doing it. However, the name of an array is already a pointer to the first element of the array, so you can simply do:
p = data;
(why does this work?): for (p=data; p < data+5; p++) |
It works because, as I said, the name of an array is also a pointer to the first element of the array. The rest is just normal pointer arithmetic.
What are the variables
i
(at line 6) and
my_cstring
(at line 8) for? I don't see them being used anywhere. Note that the variable
i
you declare at line 34 hides the one declared at line 6.
Apart from that, your code looks OK.
I'd recommend getting into the habit of being consistent with your indentation - this will help you a lot when you write more complicated code.
Also, it's better to define const variables, rather than using magic numbers. Consider your use of 5 in this program. Imagine if your teacher suddenly said to you, "Sorry, your array should have 10 elements, not 5." You'd have to go and change it everywhere. If, instead, you'd done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
const int ArraySize = 5;
int main()
{
int i = ArraySize ;
int data[ArraySize ] = {10, 20, 30, 40, 50};
char my_cstring[8] = "the fox";
int *p = NULL;
char *pc = NULL;
p = &data[0];
for(int a=0; a<ArraySize ; a++)
{
cout << data[a] << " ";
}
// etc...
|
Then all you'd have to do is change the value of ArraySize, and it would all still work.