如果你使用 malloc (或者 new) 动态创建了一段空间,注意这段空间不在 栈区(stack),而是在 堆区(heap)。而且也不是理论上的连续的空间(即便通常是连续的)。此时处理这段空间时就需要注意一些问题。如:基本数据类型经常会出现如下一些错误。
#include <stdio.h>
#include <string.h>
#include <process.h>
int main()
{
char* pStr = NULL;
const char* pStr2 = "abcd";
unsigned int index = 0;
pStr = (char*)malloc(sizeof(pStr2));
// pStr = "abcd"; // error 1
for (index = 0; i < sizeof(pStr2)/sizeof(char); index++)
{
*pStr = 'a' + index;
}// solve 1.
strcpy(pStr,pStr2);// solve 2.
// printf("%s",*pStr); // error 2
for (index = 0; i < sizeof(pStr2)/sizeof(char); index++)
{
printf("%c", *(pStr+index));
}// solve 1.
puts(pStr);// solve 2.
free(pStr);
return 0;
}//end of int main()