[英]C Initialize Character Array from Character Pointer
我的问题应该很简单。
我需要给函数一个预定义长度的char数组,但是我有一个字符指针,其长度可变,但不超过数组的长度。
这里的代码:
#define SIZE_MAX_PERSON_NAME 50
char person[SIZE_MAX_PERSON_NAME];
char* currentPerson = "John";
现在如何将John放入person数组,同时将数组的其余部分设置为0(/ NUL)?
这样我就可以
BINARY DATA: "John/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL....."
在我的记忆中?
很抱歉,如果这太愚蠢了,但我现在似乎找不到解决方法。
首先,对固定大小的数组进行零初始化:
// Using memset here because I don't know if the whole copy operation can or will be used
// multiple times. We want to be sure that the array is properly zero-initialized if the next
// string to copy is shorter than the previous.
memset(person, '\0', SIZE_MAX_PERSON_NAME);
然后,将可变大小的字符串复制到其中:
strcpy(person, currentPerson);
如果您不确定currentPerson
是否适合person
:
strncpy(person, currentPerson, SIZE_MAX_PERSON_NAME - 1);
请注意,如果出现以下情况, strncpy
还会将数组的剩余字节零初始化。
strlen(currentPerson) < SIZE_MAX_PERSON_NAME - 1
因此,您基本上有两个选择:
memset(person, '\0', SIZE_MAX_PERSON_NAME);
strcpy(person, currentPerson);
要么 :
strncpy(person, currentPerson, SIZE_MAX_PERSON_NAME - 1);
person[SIZE_MAX_PERSON_NAME - 1] = '\0';
发布此答案后,问题从C ++重新标记为C。
使用std::string
,如下所示:
// "using namespace std;" or "using std::string;", then:
string const person = currentPerson;
old_c_function( person.c_str() );
要在C级别执行操作(我建议您不要这样做),请首先使用类型常量替换不必要的#define
:
int const max_person_name_size = 50;
然后零初始化您的数组:
char person[max_person_name_size] = {};
(注意:这里没有愚蠢的memset
。)(还请注意:这种归零只是一种预防措施。您想要这样做。但是因为strcpy
可以确保尾随零字节,所以它实际上不是必需的。)
然后只需复制字符串:
assert( strlen( current_person ) < max_person_name_size );
strcpy( person, current_person );
但是不要这样做。 使用std::string
代替。
更新 :花了几分钟的时间做其他事情,使我意识到,与到目前为止所有其他答案一样,这个答案是完全错误的 。 OP在其他地方的评论中指出
”我在库中有一个仅包含字符数组的函数。 不是字符指针。
因此,这显然是一个误解。
唯一有意义的方法是通过函数修改数组,然后std::string::c_str()
不是解决方案。 但是,如果将std::string
的长度设置为足以用于C函数的长度,则仍可以使用。 可以这样:
person.resize( max_person_name_size );
foo( &person[0] ); // Assuming foo modifies the array.
person.resize( strlen( person.c_str() ) );
使用文字,您可以执行以下操作:
char person[SIZE_MAX_PERSON_NAME] = "John";
如果c-string不是文字,则必须使用strcpy
进行复制
strcpy(person, currentPerson);
这是存在strncpy
唯一原因:
将一个字符串(直到0终止符或缓冲区末尾)放入固定长度的数组中,然后将其余部分归零。
这不能确保0终止,因此可以避免其他任何情况。
7.24.2.4
strncpy
函数#include <string.h> char *strncpy(char * restrict s1, const char * restrict s2, size_t n);
2
strncpy
函数将从s2
指向的数组复制到s1
指向的数组中,最多复制n
字符(不复制跟随空字符的字符)。 308)如果复制发生在重叠的对象之间,则行为是不确定的。
3如果s2
指向的数组是短于n
字符的字符串,则将空字符附加到s1
指向的数组的副本中,直到总共写入了n
字符。
4strncpy
函数返回s1
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.