Chinaunix首页 | 论坛 | 博客
  • 博客访问: 470294
  • 博文数量: 98
  • 博客积分: 3265
  • 博客等级: 中校
  • 技术积分: 1227
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-23 00:29
文章分类

全部博文(98)

文章存档

2012年(6)

2011年(83)

2010年(9)

分类: C/C++

2011-11-28 15:27:32

Visual C++ 6.0调试通过:

#include
#include
#include

void mmcpy(char *p)
{
printf("分配前 %x\n",p); //p=st,两个指针变量都保持同一个地址
p=(char *)malloc(100);
// p=(char *)0x383138; //p=0x383138,指向了这地址,从此和st无关系了
printf("分配后 %x\n",p);
}

int main(void)
{
char ds='a';
char *st=&ds; //注意这样是错误的哦:char *st=ds;

printf("调用前 %x\n",st);
mmcpy(st);
printf("调用后 %x\n",st);
// strcpy(st, "hello");
strcpy((char *)0x383138, "hello"); //"hello"占据6个字节的空间,别忘了'\0'
// printf("%s\n",st);
printf("%s\n",(char *)0x383138);

return 0;
}

//指针也是个变量,里面保持的是地址,你给它赋另一个地址,他就指向另一个地址。它不认主人的
//虽然各个指针间赋值,但是各个指针之间没有必然的联系,是独立的。
//只是相互赋值的指针都指向了同一个地址而已

改进1:
#include //printf
#include //malloc,free
#include //strcpy

char* mmcpy(char *p)
{
p=(char *)malloc(100);
return p;
}

int main(void)
{
char *st=NULL;

st=mmcpy(st);
if(st == NULL) //是否成功分配
return (-1);
strcpy(st, "hello");
printf("%s\n",st);
free(st); //malloc后free,好习惯,必须的
return 0;
}


改进2:
#include
#include
#include

void mmcpy(char **p)
{
*p=(char *)malloc(100);
}

int main(void)
{
char *st=NULL;

mmcpy(&st);
if(st==NULL)
return (-1);
strcpy(st, "hello");
printf("%s\n",st);

free(st);

return 0;
}
阅读(1846) | 评论(0) | 转发(1) |
0

上一篇:安装VMware tools注意

下一篇:strcpy自己实现

给主人留下些什么吧!~~