正确填充炭指针

Filling char pointer correctly

本文关键字:指针 填充      更新时间:2023-10-16

我有一个char指针:

char* s = new char[150];

现在如何填充?这个:

s="abcdef";

发出有关字符串文字和 char*之间转换弃用的警告,但通常有效。

这个:

char* s = new[150]("abcdef");

不起作用,给出错误。

如何正确执行此操作?请注意,我希望内存分配具有150*sizeof(char(字节并包含" ABCDEF"。我知道Malloc,但是可以使用新的吗?

它用于我无法使用标准库的作业。

这个语句序列

char* s = new char[150];
s="abcdef";

导致内存泄漏,因为首先分配了内存,并将其地址分配给指针s,然后将指针与字符串文字"abcdef"的地址重新分配。此外,C 中的字符串文字(与C相反(具有恒定字符数组的类型。

如果您分配了字符串的内存,则应使用C标准函数strcpy或C标准函数strncpy

例如

char* s = new char[150];
std::strcpy( s, "abcdef" );

const size_t N = 150;
char* s = new char[N];
std::strncpy( s, "abcdef", N );
s[N-1] = '';

,甚至以下方式

#include <iostream>
#include <cstring>
int main()
{
    const size_t N = 150;
    char *s = new char[N]{ '' };
    std::strncpy( s, "abcdef", N - 1 );
    std::cout << s << 'n';
    delete []s;
}

在任何情况下,最好仅使用标准类std::string

std::string s( "abcdef" );

或例如

std::string s;
s.assign( "abcdef" );

创建字符串内存区域,然后在不使用C 中的标准库中填充它的基本过程:

  • 使用new
  • 创建适当的尺寸内存区域
  • 使用循环将字符从字符串复制到新区域

,源代码看起来像:

// function to copy a zero terminated char string to a new char string.
// loop requires a zero terminated char string as the source.
char *strcpyX (char *dest, const char *source)
{
    char *destSave = dest;   // save copy of the destination address to return
    while (*dest++ = *source++);   // copy characters up to and including zero terminator.
    return destSave;  // return destination pointer per standard library strcpy()
}

// somewhere in your code
char *s1 = new char [150];
strcpyX (s1, "abcdef");

给定字符数组:

char * s = new char [256];

这是填充指针的方法:

std::fill(&s, &s + sizeof(s), 0);

这是如何填充 Array

std::fill(s, s+256, '');

这是分配>或复制文本的方法

std::strcpy(s, "Hello");

您也可以使用std::copy

static const char text[] = "World";
std::copy(text, text + sizeof(text), s);

请记住,指针,数组和C风格的字符串是不同的概念和对象。

编辑1:优先 std::string
在C 中,更喜欢将std::string用于文本而不是字符数组。

std::string s;
s = "abcdef";
std::cout << s << "n";

您分配了此字符串的内存后,您可以使用strcpy填充它:

strcpy(s, "abcdef");