创建一个函数来复制 n 个字符,如 C 中的 strcpy

标签 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 这样的函数,但是有一些错误我无法自己修复。我认为它会将 n 个元素从 char* scr 复制到 char* dest,但是当我运行代码时,它崩溃了。你能帮我修复代码并向我解释一下吗?我非常感谢。

最佳答案

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

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

关于创建一个函数来复制 n 个字符,如 C 中的 strcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43031181/

相关文章:

c - 将数组附加到共享内存

c - C中的结构体到数组

c - 通过省略号发送时 `long` 和 `size_t` 的整数提升?

c++ - 在 C/C++ 的 ODBC 程序中找不到 SQL.H 和 SQLEXT.H

C99 标准 - fprintf - s 精确转换

c - 使用 .mm 和 .h 文件在 C 中声明全局变量?

c - 具有有限缓冲区的生产者/消费者

c - "undefined reference"连lib都有函数符号

c - C 中 printf 的函数

c - 启动多个 CUDA 内核是否需要返回每个内核的主机?