简体   繁体   中英

What is the pointer pointing to?

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?

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.

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 );  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM