[英]C Initialize Character Array from Character Pointer
My question should be rather simple. 我的问题应该很简单。
I need to give a function a char array of a pre-defined length, but I have a character pointer with variable length, but not longer than the length of my array. 我需要给函数一个预定义长度的char数组,但是我有一个字符指针,其长度可变,但不超过数组的长度。
Here the code: 这里的代码:
#define SIZE_MAX_PERSON_NAME 50
char person[SIZE_MAX_PERSON_NAME];
char* currentPerson = "John";
now how would I get John into the person array but also setting the rest of the array to 0 (/NUL) ? 现在如何将John放入person数组,同时将数组的其余部分设置为0(/ NUL)?
so that I would have 这样我就可以
BINARY DATA: "John/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL/NUL....."
in my memory? 在我的记忆中?
sorry if this is overly stupid, but I can't seem to find a solution right now. 很抱歉,如果这太愚蠢了,但我现在似乎找不到解决方法。
First, zero-initialize the fixed-size array : 首先,对固定大小的数组进行零初始化:
// 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);
Then, copy the variable-size string into it : 然后,将可变大小的字符串复制到其中:
strcpy(person, currentPerson);
If you are not certain that currentPerson
will fit into person
: 如果您不确定
currentPerson
是否适合person
:
strncpy(person, currentPerson, SIZE_MAX_PERSON_NAME - 1);
Note that strncpy
also zero-initialize the remaining bytes of the array if 请注意,如果出现以下情况,
strncpy
还会将数组的剩余字节零初始化。
strlen(currentPerson) < SIZE_MAX_PERSON_NAME - 1
So you basically have these two options : 因此,您基本上有两个选择:
memset(person, '\0', SIZE_MAX_PERSON_NAME);
strcpy(person, currentPerson);
Or : 要么 :
strncpy(person, currentPerson, SIZE_MAX_PERSON_NAME - 1);
person[SIZE_MAX_PERSON_NAME - 1] = '\0';
After this answer was posted the question was retagged from C++ to C. 发布此答案后,问题从C ++重新标记为C。
Use a std::string
, like this: 使用
std::string
,如下所示:
// "using namespace std;" or "using std::string;", then:
string const person = currentPerson;
old_c_function( person.c_str() );
To do things at the C level, which I recommend that you don't, first replace the unnecessary #define
with a typed constant: 要在C级别执行操作(我建议您不要这样做),请首先使用类型常量替换不必要的
#define
:
int const max_person_name_size = 50;
Then zero-initialize your array: 然后零初始化您的数组:
char person[max_person_name_size] = {};
(Note: no silly memset
here.) (Also note: this zeroing is only a preventive measure. You wanted it. But it's not really necessary since strcpy
will ensure a trailing zero-byte.) (注意:这里没有愚蠢的
memset
。)(还请注意:这种归零只是一种预防措施。您想要这样做。但是因为strcpy
可以确保尾随零字节,所以它实际上不是必需的。)
Then just copy in the string: 然后只需复制字符串:
assert( strlen( current_person ) < max_person_name_size );
strcpy( person, current_person );
But don't do this. 但是不要这样做。 Use
std::string
instead. 使用
std::string
代替。
Update : doing other things for some minutes made me realize that this answer, as all the others so far, is completely off the mark . 更新 :花了几分钟的时间做其他事情,使我意识到,与到目前为止所有其他答案一样,这个答案是完全错误的 。 The OP states in a comment elsewhere that
OP在其他地方的评论中指出
” I've got a function in the library which only takes a character array.
”我在库中有一个仅包含字符数组的函数。 Not a character pointer.
不是字符指针。
Thus, apparently it's all about a misconception. 因此,这显然是一个误解。
The only way this can make sense is if the array is modified by the function, and then std::string::c_str()
is not a solution. 唯一有意义的方法是通过函数修改数组,然后
std::string::c_str()
不是解决方案。 But a std::string
can still be used, if its length is set to something sufficient for the C function. 但是,如果将
std::string
的长度设置为足以用于C函数的长度,则仍可以使用。 Can go like this: 可以这样:
person.resize( max_person_name_size );
foo( &person[0] ); // Assuming foo modifies the array.
person.resize( strlen( person.c_str() ) );
With literal, you may do: 使用文字,您可以执行以下操作:
char person[SIZE_MAX_PERSON_NAME] = "John";
if c-string is not a literal, you have to do the copy with strcpy
如果c-string不是文字,则必须使用
strcpy
进行复制
strcpy(person, currentPerson);
This is the one and only reason for the existence of strncpy
: 这是存在
strncpy
唯一原因:
Putting a string (up to the 0-terminator or buffer end) into a fixed-length array and zeroing out the rest. 将一个字符串(直到0终止符或缓冲区末尾)放入固定长度的数组中,然后将其余部分归零。
This does not ensure 0-termination, thus avoid it for anything else. 这不能确保0终止,因此可以避免其他任何情况。
7.24.2.4 The
strncpy
function7.24.2.4
strncpy
函数#include <string.h> char *strncpy(char * restrict s1, const char * restrict s2, size_t n);
2 The
strncpy
function copies not more thann
characters (characters that follow a null character are not copied) from the array pointed to bys2
to the array pointed to bys1
.2
strncpy
函数将从s2
指向的数组复制到s1
指向的数组中,最多复制n
字符(不复制跟随空字符的字符)。 308) If copying takes place between objects that overlap, the behavior is undefined.308)如果复制发生在重叠的对象之间,则行为是不确定的。
3 If the array pointed to bys2
is a string that is shorter thann
characters, null characters are appended to the copy in the array pointed to bys1
, untiln
characters in all have been written.3如果
s2
指向的数组是短于n
字符的字符串,则将空字符附加到s1
指向的数组的副本中,直到总共写入了n
字符。
4 Thestrncpy
function returns the value ofs1
.4
strncpy
函数返回s1
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.