读书人

malloc()的有关问题

发布时间: 2012-03-08 13:30:13 作者: rapoo

malloc()的问题
我写两个程序,第一个吧malloc()放在main()里面,程序可以输出为abc
第二个放在test()里面,程序输出为null。

能否做到:
1、malloc()在test()内分配内存并赋值"abc"
2、通过test()的参数x返回"abc",而不是通过return返回。

//////////////////////////////////////
// 1)把malloc()放在main()函数里

#include <stdio.h>
#include <string.h>
#include <malloc.h>

void test(char * x)
{
strcpy(x, "abc");
}

int main(void)
{
char *s = NULL;
s = (char *)malloc(sizeof(char) * 10);
test(s);
printf("%s\n", s); //显示abc
return 0;
}

//////////////////////////////////////
// 2)把malloc放在test()函数里

#include <stdio.h>
#include <string.h>
#include <malloc.h>

void test(char * x)
{
x = (char *)malloc(sizeof(char) * 10);
strcpy(x, "abc");
}

int main(void)
{
char *s = NULL;
test(s);
printf("%s\n", s); //显示null
return 0;
}

[解决办法]
放在test()里面要改成
void test(char ** x)
{
*x = (char *)malloc(sizeof(char) * 10);
strcpy(*x, "abc");
}
调用时test(&s);

[解决办法]

C/C++ code
#include <stdio.h>#include <string.h>#include <malloc.h>void test(char ** x){   *x = (char *)malloc(sizeof(char) * 10);   strcpy(*x, "abc");}int main(void){   char *s = NULL;   test(&s);   printf("%s\n", s); //显示null   return 0;}
[解决办法]
test(s);
你这么调用时,使得形参x与实参s指向了同一个地方,所以对x写入的值s能读出来。

而你第二段程序中,调用test(s)的时候,x和s还是指向同一个地方的(NULL),
而x = (char *)malloc(sizeof(char) * 10);之后,x已经指向了一个新的地方(malloc分配给它的),但s始终没有动过,还是指向NULL,所以打印结果是null。

读书人网 >C++

热点推荐