一道指针内存题目的三个改法

来源:互联网 发布:三星scx3401扫描软件 编辑:程序博客网 时间:2024/06/01 21:57

原来的题目为

GetMemory(char   *p)
{
          p=(char   *)malloc(100);
}
main()
{
          char   *str=NULL;
          GetMemory(str);
          strcpy(str, "hello ");
          printf(str);

可以返回新申请内存的地址.改法如下:

unsigned int GetMemory(char *p)  
{  
    p=(char *)malloc(100);
 return (unsigned int)&p;
}  
main()  
{  
       char   *str=NULL;
    unsigned int addr;
       addr=GetMemory(str);
    str = (char*)*( (unsigned int *)addr );
       strcpy(str, "hello   ");  
       printf(str);
    free(str);
    str=NULL;
}

也可以用指针引用.改法如下:

#include <stdio.h>
#include <malloc.h>
#include <string.h>
void GetMemory(char * &p)  
{  
    p=(char *)malloc(100);  
}  
void main()  
{  
       char   *str=NULL;  
       GetMemory(str);  
       strcpy(str, "hello   ");  
       printf(str);
    printf("%x",str);
    free(str);
    str=NULL;
   //rintf("%x",str);
}

还可以用指向指针的指针.改法如下:

void GetMemory(char ** p)
{  
    *p=(char *)malloc(100);  
}  
void main()  
{  
       char   *str=NULL;
 
       GetMemory(&str);  
       strcpy(str, "hello   ");  
       printf(str);
    free(str);
    str=NULL;

原创粉丝点击