#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct _Person{
char name[20] ;
int age ;
}Person ;
//typedef struct _Student{
// Person *p ;
// float score ;
//}Student ;
Person *getPerson(){
static Person* p = NULL ;//或者放置全局变量里
if(NULL != p){
return p ;
}
p = (Person* )malloc(sizeof(Person)) ;
assert(NULL != p);
return p ;
}
int main(){
Person* p1 = getPerson() ;
const char *name = "zhangsan" ;
strncpy(p1->name , name , strlen(name)) ;
printf("name of p1 is %s\n" , p1->name) ;
Person *p2 = getPerson() ;
printf("name of p2 is %s\n" , p2->name) ;//
return 0 ;
}
输出:
name of p1 iszhangsan
name of p2 iszhangsan
参考:
1.http://blog.csdn.net/feixiaoxing/article/details/7071202