gpt4 book ai didi

c - 为什么整数在 printf 中格式化指针时需要一个符号,而字符数组在 C 中不需要?

转载 作者:行者123 更新时间:2023-12-02 06:26:44 24 4
gpt4 key购买 nike

具体来说,当我想格式化所述整数的指针时。我正在学习 The Art of Exploitation,它在以下代码片段中给我留下了深刻的印象。

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
int value = 5;
char buffer_one[8], buffer_two[8];

strcpy(buffer_one, "one"); /* Put "one" into buffer_one. */
strcpy(buffer_two, "two"); /* Put "two" into buffer_two. */

printf("[BEFORE] buffer_two is at %p and contains \'%s\'\n", buffer_two, buffer_two);
printf("[BEFORE] buffer_one is at %p and contains \'%s\'\n", buffer_one, buffer_one);
printf("[BEFORE] value is at %p and is %d (0x%08x)\n", &value, value, value);

printf("\n[STRCPY] copying %d bytes into buffer_two\n\n", strlen(argv[1]));
strcpy(buffer_two, argv[1]); /* Copy first argument into buffer_two. */

printf("[AFTER] buffer_two is at %p and contains \'%s\'\n", buffer_two, buffer_two);
printf("[AFTER] buffer_one is at %p and contains \'%s\'\n", buffer_one, buffer_one);
printf("[AFTER] value is at %p and is %d (0x%08x)\n", &value, value, value);
}

最佳答案

虽然 buffer_onechar[8] 类型,但在某些情况下,例如当作为函数参数传递时,它衰减到指向数组第一个元素的指针。该指针将是 char* 类型。

由于strcpy的第一个参数应该是char*类型,所以编译成功。

关于c - 为什么整数在 printf 中格式化指针时需要一个符号,而字符数组在 C 中不需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59545516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com