问题描述
这是我的源代码:
void getData(char * theData)
{
theData = malloc(500);
strcpy(theData," hello world ...");
printf(" ; \\\
%s\\\
",海图); // OK
}
void main()
{
char * data;
getData(& data);
printf(" \ n%s \ n",data); // = NULL ???
}
malloc没问题,进入函数我得到了我想要的东西,但数据相等
到main()中为NULL。
有什么问题?
感谢您的帮助。
thierry
Hi,
Here is my source code :
void getData(char *theData)
{
theData = malloc(500);
strcpy(theData,"hello world...");
printf("\n%s\n",theData); // OK
}
void main()
{
char *data;
getData(&data);
printf("\n%s\n",data); // = NULL ???
}
malloc is ok, into the function I get what I want, but data is equal
to NULL in main().
What is the problem ?
thanks for your help.
thierry
推荐答案
仅提供main()中的数据地址是不够的。 getData()
函数必须正确使用它。像这样:
void getData(char ** theData){
* theData = malloc(500);
if(* theData){
strcpy(* theData," Hello world");
printf("%s \ n",* theData);
}
}
我认为有点像为函数分配新值
参数的消息是一个标志设计问题每隔5分钟就可以帮助治疗这个非常常见的新手'
问题。
PS。你也应该用int main()替换void main()。
-
/ - Joona Palaste(pa ***** @ cc .helsinki.fi)-------------芬兰-------- \
\-- -------------- -------规则! -------- /
我正在寻找自己。你在某个地方见过我吗?"
- Anon
It is not enough to supply the address of data in main(). The getData()
function must use it correctly. Like so:
void getData(char **theData) {
*theData = malloc(500);
if (*theData) {
strcpy(*theData, "Hello world");
printf("%s\n", *theData);
}
}
I think a message somewhat like "Assigning new values to function
parameters is a sign of a design problem" every 5 minutes to
comp.lang.c might help a little to cure this very common newbies''
problem.
PS. You also should replace void main() by int main().
--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"I am looking for myself. Have you seen me somewhere?"
- Anon
什么是&数据?它是指向char *的指针,对吗?所以& data是一个char **,它不是
不是getData作为参数的东西。
void getData(char ** theData){
* theData = malloc(500);
如果(!* theData)返回; / *检查NULL * /
strcpy(* theData," Hello,world!");
printf(" \ n%s \ n" ;,* theData);
}
此外,main()* always *返回一个int。 void main()错了。
-
Christopher Benson-Manica |在你的命运转向轮子,
ataru(at)cyberspace.org |在你的课上学习。
What is &data? It''s a pointer to a char*, right? So &data is a char**, which
is not what getData takes as a parameter.
void getData(char **theData) {
*theData=malloc(500);
if( !*theData ) return; /* check for NULL */
strcpy( *theData, "Hello, world!" );
printf( "\n%s\n", *theData );
}
Also, main() *always* returns an int. void main() is wrong.
--
Christopher Benson-Manica | Upon the wheel thy fate doth turn,
ataru(at)cyberspace.org | upon the rack thy lesson learn.
这篇关于malloc问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!