创建一个函数来复制像c中的strcpy一样的c char

时间:2017-03-26 16:10:29

标签: c

#include <stdio.h>
#include <stdlib.h>
void nhap(char* &scr, int *n)
{
    do
    {
        printf("Input the string length:\n");
        scanf_s("%d", n);
    } while (n < 0);

    scr = (char*)malloc(*n * sizeof(char));
    for (int i = 0; i < *n; i++)
    {
        scanf_s("%c", (scr + i));
    }
}

void xuat(char* scr, int n)
{
    printf("\nThe content of string: ");
    for (int i = 0; i < n; i++)
    {
        printf("%c", *(scr + i));
    }
}

char* StringNCopy(char* dest, char* scr, int n)
{
    if (n == NULL)
    {
        return NULL;
    }
    dest = (char*)realloc(dest, n * sizeof(char));
    for (int i = 0; i < n; i++)
    {
        for (int j = *(scr + n); j > 0; j--)
        {
            *(dest + i) = *(scr + j);
        }
    }
    *(dest + n) = '\0';
    return dest;
}


void main()
{

    char *a;
    char *b=NULL;
    int n;
    nhap(a, &n);
    xuat(a, n);
    StringNCopy(b, a, 4);
    printf("%s", *b);
    free(a);
}

对不起,我有一个问题,我想创建一个像strcpy这样的函数,但有些错误我自己无法解决。我认为它会将char * scr中的n个元素复制到char * dest,但是当我运行我的代码时,它会崩溃。你能帮我解决一下代码并向我解释一下吗?我非常感谢。

1 个答案:

答案 0 :(得分:1)

for循环应该是这样的

for (int i = 0; i < n; i++)
    {
        *(dest + i) = *(scr + i);
    }

你不需要嵌套for循环,因为你只需要遍历数组一次并复制值。

更正的计划

#include <stdio.h>
#include <stdlib.h>
void nhap(char* &scr, int *n)
{
    do
    {
        printf("Input the string length:\n");
        scanf("%d", n);
    } while (n < 0);

    scr = (char*)malloc((*n+1) * sizeof(char));    //allocated size should be n+1
    fflush(stdin);
    for (int i = 0; i < *n; i++)
    {
        scanf("%c", (scr+i ));
    }

}

void xuat(char* scr, int n)
{

    printf("\nThe content of string: ");
    for (int i = 0; i < n; i++)
    {
        printf("%c", *(scr + i));
    }
}

void StringNCopy(char* &dest, char* &scr, int n)     //no need to return the string aas you can pass it as reference
{

    if (n == NULL)
    {
        return;
    }

    dest = (char*)realloc(dest, (n+1) * sizeof(char));  //alloted size should be n+1
    for (int i = 0; i < n; i++)
    {

            *(dest + i) = *(scr + i);         //no need of nested loops

    }
    *(dest + n) = '\0';

}


int main()
{

    char *a;
    char *b=NULL;
    int n;
    nhap(a, &n);

    xuat(a, n);
    StringNCopy(b, a, 4);

    printf("\n6%s", b);
    free(a);
}

经过测试并正常工作。
观察评论中提到的错误