Lorry Astra
2010-05-29 12:08:01 UTC
Hi friends,
here's a code sample:
void mallocate(char*);
int main()
{
char* c = NULL;
mallocate(c);
// strcpy(c,"ab"); Here "strcpy" is an error, because c is still NULL
return 0;
}
void mallocate(char* p)
{
p = malloc(3*sizeof(char));
return;
}
In my opinion, I pass a char pointer from "main" to "mallocate", that means
I pass an pointer to "mallocate", In "mallocate", I allocate memory for
pointer "p", but why I can not get it from "main" function? I think I don't
grasp the root cause, Could anybody describe for me? Thank you.
==============================
By the way, I know the correct way is:
void mallocate(char** p)
{
*p = malloc(3*sizeof(char));
return;
}
or
char* mallocate(char* p)
{
p = malloc(3*sizeof(char));
return p;
}
===============================
Thank you.
Lorry
here's a code sample:
void mallocate(char*);
int main()
{
char* c = NULL;
mallocate(c);
// strcpy(c,"ab"); Here "strcpy" is an error, because c is still NULL
return 0;
}
void mallocate(char* p)
{
p = malloc(3*sizeof(char));
return;
}
In my opinion, I pass a char pointer from "main" to "mallocate", that means
I pass an pointer to "mallocate", In "mallocate", I allocate memory for
pointer "p", but why I can not get it from "main" function? I think I don't
grasp the root cause, Could anybody describe for me? Thank you.
==============================
By the way, I know the correct way is:
void mallocate(char** p)
{
*p = malloc(3*sizeof(char));
return;
}
or
char* mallocate(char* p)
{
p = malloc(3*sizeof(char));
return p;
}
===============================
Thank you.
Lorry