C 从字符指针初始化字符数组

标签 c arrays pointers char initialization

我的问题应该很简单。

我需要给一个函数一个预定义长度的字符数组,但我有一个可变长度的字符指针,但不长于我的数组长度。

这里是代码:

#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/

相关文章:

c - 使用非标准名称链接 C 库

c++ - 多线程代码中缓存友好的数组迭代模式

c - "multidimensional array pointer +1"的值不匹配

arrays - 返回数组时类型不匹配

C 在函数中返回数组

c - 包含包含指向自身的结构指针的 union 的结构使用 '.' 访问而不是 '->' ,混淆

c - 在函数名后声明函数参数

c - 没有使用 malloc 分配内存

c - 在 C 的另一个结构中初始化和访问嵌套的 struct char 指针

c++ - 字符指针比较错误