“Hello World”由编译器静态分配。它是程序的一部分,存在于程序可寻址的某个位置;称它为地址 12。
charVoidPointer 最初指向 malloc 为您分配的某个位置;称它为地址 98。
charVoidPointer = "Hello ..." 导致 charVoidPointer 指向程序中的数据;地址 12。您丢失了之前包含在 charVoidPointer 中的地址 98。
而且你不能释放不是由 malloc 分配的内存。
为了更从字面上说明我的意思:
void* charVoidPointer = malloc(sizeof(char) * 256);
printf("the address of the memory allocated for us: %p\n", charVoidPointer);
charVoidPointer = "Hello World";
printf("no longer the address allocated for us; free will fail: %p\n",
charVoidPointer);
你的意思是:
strcpy(charVoidPointer, "Hello World");
编辑:其他类型的寻址内存示例
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
// an array of 10 int
int *p = (int*)malloc(sizeof(int) * 10);
// setting element 0 using memcpy (works for everything)
int src = 2;
memcpy(p+0, &src, sizeof(int));
// setting element 1 using array subscripts. correctly adjusts for
// size of element BECAUSE p is an int*. We would have to consider
// the size of the underlying data if it were a void*.
p[1] = 3;
// again, the +1 math works because we've given the compiler
// information about the underlying type. void* wouldn't have
// the correct information and the p+1 wouldn't yield the result
// you expect.
printf("%d, %d\n", p[0], *(p+1));
free (p);
}
实验; 将类型从 int 更改为 long、double 或某些复杂类型。