我的代码有什么问题(使用指针复制字符串?)?

时间:2015-03-14 09:42:56

标签: c pointers

//a function that copies one string to another
copy(char *,char*);
main()
{
    char one[20],two[20];
    printf("enter two sentences \n\n");
    gets(one);//first string
    gets(two);//second string
    copy(one,two);
    printf("%s",two);
}
copy(char *s1,char *s2)
{
    while(*s1!='\0')
    {
        s2=s1;
        s1++;
        s2++;
    }
    s2='\0';
}

上述程序有什么问题?为什么字符串' one'没有被复制到字符串'两个'请在指针

的帮助下解释

2 个答案:

答案 0 :(得分:2)

这是因为:

s2 = s1;

更改指针 s2,使其指向s1的内容。

您要做的是复制内容:

*s2 = *s1;

一个不错的编译器也应该在这一行给你一个警告:

s2 = '\0';

因为您要将char分配给char *。它应该是:

*s2 = '\0';

实施这些更改后,函数将会是(包括使用一些,IMNSHO,更好的变量名称):

void copy (char *from, char *to) {
    while (*from != '\0') {
        *to = *from;
        from++;
        to++;
    }
    *to = '\0';
}

或者,一旦你的大脑像我一样被几十年的C使用扭曲了: - )

void copy (char *from, char *to) {
    while (*to++ = *from++);
}

答案 1 :(得分:1)

#include <stdio.h>
#include <string.h> /* for strchr */

void copy(const char *, char*); /* use void to return nothing */

int main(void) /* main() is not valid */
{
    char one[20], two[20];
    char *ptr;

    printf("enter two sentences \n\n");
    /* gets is deprecated, use fgets in order to avoid overflows */
    fgets(one, sizeof one, stdin);
    /* fgets leaves a trailing newline, remove it */
    if ((ptr = strchr(one, '\n'))) *ptr = '\0';
    fgets(two, sizeof two, stdin); /* why? is gonna be replaced by one */
    copy(one, two);
    printf("%s\n", two);
    return 0;
}

void copy(const char *s1, char *s2) /* s1 is not modified, use const */
{
    while(*s1 != '\0')
    {
        *s2 = *s1; /* Don't assign addresses, assign values */
        s1++;
        s2++;
    }
    *s2 = '\0';
}