我正在尝试写入我使用 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("%016Xn", heap[i]);
heap[i] = "AAA";
printf("%pn", heap[i]);
i++;
}
}
这是我得到的输出
0000000000000000
0xc7
0000000000000000
0xc7
了解C中的"字符串"和'c'字符之间的差异。尝试此代码:
#include <stdio.h>
int main(){
/* Usual way */
char *a = "A";
char *b = "B";
char *c = "C";
printf("Address of a = 0x%xn",a);
printf("Address of b = 0x%xn",b);
printf("Address of c = 0x%xn",c);
/* Explicit way - Because you asked above question */
printf("This is Base Address of String A = 0x%xn","A");
printf("This is Base Address of string B = 0x%xn","B");
printf("This is Base Address of string C = 0x%xn","C");
/* Now, let us print content - The usual way */
printf("Pointer value a has %xn",*a);
printf("Pointer value b has %xn",*b);
printf("Pointer value c has %xn",*c);
/* The unusual way */
printf("Value of String A %xn",*"A");
printf("Value of String B %xn",*"B");
printf("Value of String C %xn",*"C");
}
上面的代码将生成编译器警告,因为char *格式为未签名的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
首先,您正在进行一些操作而不真正知道含义:
while (i < 2)
{
printf("%016Xn", 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("%pn", heap[i]); // You are printing a pointer, why?
i++;
}
C中的字符只能包含一个字符。因此,这有一种理解:
char a = 'b';
,如果您想拥有一个字符串,则需要一个char的数组:
char * a = "AAA";
以获取更多阅读此处的阅读
因此,我将以这种方式重写代码:
while (i < 2){
printf("First: %cn",heap[i]);
heap[i] = 'a';
printf("After: %cn",heap[i]);
i++;
}