gpt4 book ai didi

c - 字节打印和写入

转载 作者:行者123 更新时间:2023-11-30 16:49:49 34 4
gpt4 key购买 nike

我正在尝试写入使用malloc()分配的字节。我真的很难正确打印出位和值。

int main(){

unsigned char *heap = (unsigned char *) malloc( 2 * sizeof(char)); //allocate two bytes

int n= 2, i =0;
unsigned char* byte_array = heap;

while (i < 2) //trying to write over the first byte then print out to verify
{
printf("%016X\n", heap[i]);
heap[i] = "AAA";
printf("%p\n", heap[i]);
i++;
}
}

这是我得到的输出

0000000000000000
0xc7
0000000000000000
0xc7

最佳答案

要了解 C 中“string”和“c”字符之间的区别,请尝试以下代码:

#include <stdio.h>

int main(){

/* Usual way */
char *a = "A";
char *b = "B";
char *c = "C";

printf("Address of a = 0x%x\n",a);
printf("Address of b = 0x%x\n",b);
printf("Address of c = 0x%x\n",c);

/* Explicit way - Because you asked above question */
printf("This is Base Address of String A = 0x%x\n","A");
printf("This is Base Address of string B = 0x%x\n","B");
printf("This is Base Address of string C = 0x%x\n","C");

/* Now, let us print content - The usual way */
printf("Pointer value a has %x\n",*a);
printf("Pointer value b has %x\n",*b);
printf("Pointer value c has %x\n",*c);

/* The unusual way */
printf("Value of String A %x\n",*"A");
printf("Value of String B %x\n",*"B");
printf("Value of String C %x\n",*"C");

}

上面的代码会生成编译器警告,因为 char * 的格式为 unsigned int,但忽略它即可理解示例。

输出如下所示:

Address of a = 0xedfce4a
Address of b = 0xedfce4c
Address of c = 0xedfce4e
This is Base Address of String A = 0xedfce4a
This is Base Address of string B = 0xedfce4c
This is Base Address of string C = 0xedfce4e
Pointer value a has 41
Pointer value b has 42
Pointer value c has 43
Value of String A 41
Value of String B 42
Value of String C 43

关于c - 字节打印和写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42451752/

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