Help with a pointer exercise in the C programming language
I have the following exercise to do from Tim Ward's online C tutorial:
Define a character array and use "strcpy" to copy a string into it. Print the string out by using
a loop with a pointer to print out one character at a time. Initialize the pointer to the first element
and use the double plus sign to increment the pointer. Use a separate integer variable to count
the characters to print.
I've been able to make a loop and have the pointer point to each character in the array using the loop variable as the index for the array and displaying them. Here is my code:
Code:
# include <stdio.h>
main()
{
char x[13], *pt;
int index;
strcpy(x,"Hello world!");
for(index=0;index<13;index++)
{
pt = x + index;
printf("%c",*pt);
}
getch();
}
The exercise is asking me to actually increment the pointer each loop, which I'm guessing is increasing the memory address by 1, But I'm not too sure. Anyway, I've tried this code, which doesn't work.
Code:
#include <stdio.h>
main()
{
char x[13], *pt;
int index;
strcpy(x,"Hello world!");
for(index=0;index<13;index++)
{
pt = x;
printf("%c",*pt);
pt++;
}
getch();
}
Now that I look at this code for a few minutes, I realize that it doesn't make sense. I'm dumbfounded on how I would increment this pointer to display each character in my char array and printing them out. Perhaps I'm confused on what this exercise is asking me to do.
Help would be appreciated.
Thanks.