我的问题应该很简单。
我需要给一个函数一个预定义长度的字符数组,但我有一个可变长度的字符指针,但不长于我的数组长度。
这里是代码:
#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 从字符指针初始化字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25110302/