编写一个函数,将字符串文本复制到指针给出的 char 数组中

Writing a function that copies a string literal into a char array given by a pointer

本文关键字:指针 复制 数组 char 文本 字符串 一个 函数      更新时间:2023-10-16

这是针对类项目的一部分。这不是必需的,但是现在我一次分配一个字符,它会在我的代码中添加数十行。我想编写一个函数,该函数将接受字符串文字和指针,并将文字复制到指向的数组中。

它看起来像这样。

char* word = new char[12];
stringCopy(word, "thisisaword");
cout << word;

该程序会将"thisisaword"打印到屏幕上。

因为这是针对一堂课的,所以我能做的有限。

-

-我必须精确地动态分配和调整数组大小(通过使用临时的、未调整大小的数组并找到它们的长度来分配大小精确的新数组(

-

-我不能使用任何字符串库函数,我必须自己编写

-

-我不能使用重载运算符

到目前为止,我还没有尝试过任何来实现这一点,因为我不知道如何实现。我已经编写了一个函数,该函数在给定两个指针的情况下执行此操作,这非常简单,我不需要发布其代码。strlen 源,删除,然后将正确的数量分配给目标指针,然后在由字符串长度控制的循环中逐个字符复制。

我喜欢

这些任务。这是我的解决方案:

#include <iostream>
struct P { char const* s; std::size_t z; };
template <std::size_t z>
P s(char const(&s)[z]) { return { s, z }; }
int main()
{
    auto p(s("thisisaword"));
    char* word = new char[p.z];
    for (auto i(0);  (i<:word:> = i<:p.s:>); ++i) <%%>
    std::cout << word << 'n';
    delete[] word;
}