正确填充炭指针
Filling char pointer correctly
我有一个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");
相关文章:
- 使用结构成员指针在C++中填充结构
- 如何使用数据成员填充派生类的对象到基类的指针数组中
- 在循环(C++)中用新指针填充映射
- 用基于范围的for循环填充指针向量
- 内存集不会填充整个指针数组 c++
- 如何填充包含指针数组的结构数组
- 使用指向数组的指针填充动态数组
- 操作员的地址可以启动指针,但填充值是垃圾
- 正确填充炭指针
- C++传递指向未知大小的数组的指针,函数大小并填充它
- 在使用结构体和用函数填充其变量(使用指针)时遇到问题
- 使用来自函数的指针填充结构数组
- 如何在文本文件中逐行读取并填充指向对象数组的指针
- 如何从文本文件中填充指针数组
- 通过指针填充自定义的类 - 与构造函数的麻烦
- 如何使用类实例成员函数指针填充函数指针成员
- 将指针填充到向量的向量会产生奇怪的结果
- 使用指针填充向量时出现分段错误
- 通过返回的指针填充私有字段
- 用指针填充列表 - c++