c - 字节打印和写入

标签 c memory malloc bit-manipulation

我正在尝试写入使用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/

相关文章:

Python字典和集合内存分配

c++ - 使用 C++,我在创建类时得到 0xcdcdcdcd 指针——发生了什么?

c - printf 只显示 char* 的 24 个字符

c - 是在函数内部重新声明结构体还是将其声明为静态并每次都设置为 0 更好?

c - 从 C 执行程序

caching - 我可以直接将数据存储在处理器缓存中吗?

c - 段错误,分配给c中的双指针

scanf() 损坏的 malloc 区域

c - 来自 mips 路由器上的 clock_gettime() 的纳秒

c - Stackoverfflow 与 Msys2