很多人看到这段代码后,想着答案肯定是“hello world”。那么你错了,这段代码的运行结果是空的。为什么呢?我们来分析一下。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *p)
{
p=(char*)malloc(100);
strcpy(p,"hello world");
}
int main()
{
char *str=NULL;
getmemory(str);
printf("%s\n",str);
free(str);
return 0;
}
那么p和str公用一块内存,p的内容改变的同时,str也改变了。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *&p)
{
p=(char*)malloc(100);
strcpy(p,"hello world");
}
int main()
{
char *str=NULL;
getmemory(str);
printf("%s\n",str);
free(str);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char **p)
{
*p=(char*)malloc(100);
strcpy(*p,"hello world");
}
int main()
{
char *str=NULL;
getmemory(&str);
printf("%s\n",str);
free(str);
return 0;
}
想到结果了吗?#include <string.h>
#include <stdio.h>
static const char *msg[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
char *get_a_day(int idx)
{
static char buf[20];
strcpy(buf, msg[idx]);
return buf;
}
int main(void)
{
printf("%s %s\n", get_a_day(0), get_a_day(1));
return 0;
}