Converting\casting 指向字符串的空指针

Converting\casting a void pointer to a string

我该怎么做,因为我不知道我是否可以读取 void 指针,所以我想先将其转换为字符串。这是我在测试时的尝试:

void* test1;
char test2[] = "ha 21";
char test3[50];

test1 = test2;

test3 = test1;

printf("%s", test3);

return 0;

当我尝试使 test1 = test 2 可能也是错误的,但这只是为了显示 void 指针中应该包含的内容。我只是想看看如何将包含字符串的空指针转换为字符串。

因为test3是一个数组类型,所以不能赋值。 在 C 中,您可以将每个指针转换为 void * 并返回(隐式转换)。

所以一个可能的解决方案是将 test3 声明为指针:

void *test1;
char test2[] = "ha 21";
char *test3;

test1 = test2;
test3 = test1;

printf("%s", test3);

或者如果你想复制内存(如评论中所述):

void *test1;
char test2[] = "ha 21";
char test3[50];

test1 = test2;
strcpy(test3, test1);

printf("%s", test3);

When I try to make test1 = test2 is probably wrong as well but that is just to show what should be in the void pointer.

test1 = test2 完全正确。来自 C 标准#6.3.2.3p1

1 A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

这个语句有问题:

test3 = test1;

test3 是一个数组,您不能将 test1 分配给 test3,因为在 C 中,数组名称是不可修改的左值。

相反,您应该将 test1 的内容复制到 test3,您可以为此使用 strcpy()

但是 strcpy() 并不安全,因为它无法知道目标缓冲区有多大,如果目标缓冲区的长度不足以容纳源字符串(包括空终止字符)。在复制字符串之前,如果您可以确保目标缓冲区的长度足以容纳源字符串(包括空终止字符),那么使用 strcpy() 将源字符串复制到目标缓冲区就完全没问题了。在您的情况下,由于目标缓冲区大小为 50,足以容纳源字符串 "ha 21",因此您可以安全地使用 strcpy()。所以,而不是这个:

test3 = test1;

你应该这样做:

strcpy(test3, test1);

补充:

strncpy() 不是 strcpy() 的更安全版本。
在此处阅读有关 why strncpy() is introduced?

的信息

但是,您可以使用 strncpy() 作为替代方案(大多数开发人员都这样做),因为它可以防止缓冲区溢出,但请记住,如果源是长于要从源复制的最大字符数。您需要明确处理源长于目标的这种情况。