Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

c - why strcpy return char * and not char

A lot of string functions return a pointer but What are the Advantages of return a pointer to destination and return destination?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *sstrcpy ( char *destination, const char *source ){ //return a pointer to destination

    while ((*destination++ = *source++));
    *destination='';

return destination;
}

char sstrcpy2 ( char *destination, const char *source ){ //return destination

    while ((*destination++ = *source++));
    *destination='';

    return *destination;
}

int main(void){
    char source[] = "Well done is better than well said";
    char destination[40];

    sstrcpy ( destination, source );
    printf ( "%s
", destination);



    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The idea is to give the possibility to chain the functions. I.e. to pass one function result as a parameter to another one.

sstrcpy ( destination2, sstrcpy ( destination1, source ));

As for the proposed sstrcpy2 - it will only return a single, the last character of the copied string, which is apparently in your implementation, which is rather useless in most cases.

Update:
Note that the implementation sstrcpy is incorrect as is, it will return the value of destination, which was already moved to the end of the string, and not the pointer to the beginning of it. Alternatively I would suggest saving the original pointer and increment it's copy instead:

char *sstrcpy ( char *destination, const char *source ){ //return a pointer to destination

    char *dst = destination;
    while ((*dst++ = *source++));
    *dst='';

    return destination;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...