What is the pointer pointing to?

74 views Asked by At

I am new to C and have been reading Kernighan and Ritchie in my spare time for the last 2 months and also trying to practice it on my Linux VM. I am in the chapter on pointers and need a clarification. In the chapter, a function is given to copy the contents from one array to another using pointers.

void strcpy(char *s, char *t) {

while ((*s++=*t++)!='\0') ;


}

My doubts are

1) when I execute this on the pointer s, then in the end does it point to '\0'?

2) if I want to refer to the second last element of the array do I use *(s-2) ?

3) how do I print out all the characters stored in the array using the pointer?

2

There are 2 answers

0
Sergey Kalinichenko On BEST ANSWER

When I execute this on the pointer s, then in the end does it point to '\0'?

No, it does not. Due to post-incrementing, at the end of the loop s points one char past '\0'.

If I want to refer to the second last element of the array do I use *(s-2)?

That would be the last character of the string, assuming that your C string is not empty

How do I print out all the characters stored in the array using the pointer?

You cannot do it, unless you store the initial value of the pointer before going into the loop, or counting the number of copied characters. You cannot walk a C string backward to find its beginning, because there is no suitable "marker" there.

0
user3629249 On
1) when I execute this on the pointer s, then in the end does it point to '\0'?
as mentioned elsewhere, s will point to one past the '\0' at the end of s string

2) if I want to refer to the second last element of the array do I use *(s-2) ?
no, rather use s[strlen(s)=2]

3) how do I print out all the characters stored in the array using the pointer?
save the s pointer to a local variable before entering the loop
char *pSavedS = s;
then append, after the end of the loop, the line:
printf( "%s", pSavedS );