我试图写入我使用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
答案 0 :(得分:0)
了解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
答案 1 :(得分:0)
首先,你在没有真正了解其含义的情况下进行一些操作:
while (i < 2)
{
printf("%016X\n", heap[i]); // You're printing the value of heap[i] in hexadecimal that
// is not even setted
heap[i] = "AAA"; // This operation has no sense, 'cause a
// "char" can only contain 1 character
printf("%p\n", heap[i]); // You are printing a pointer, why?
i++;
}
C中的char只能包含一个字符。所以这有道理:
char a = 'b';
如果你想要一个字符串,你需要一个char数组:
char * a = "AAA";
更多阅读here
所以我会用这种方式重写代码:
while (i < 2){
printf("First: %c\n",heap[i]);
heap[i] = 'a';
printf("After: %c\n",heap[i]);
i++;
}