Pointers to string in functions
it seems i'm stuck with some basics. Can someone explain me why next code:
#include <stdlib.h> void Test1(char *t) { t = (char *)malloc(11); strcpy(t, "1234567890"); } void Test2(char **t) { *t = (char *)malloc(11); strcpy(*t, "1234567890"); } void Test3(char *t) { strcpy(t, "1234567890"); } char * Test4(char *t) { t = (char *)malloc(11); strcpy(t, "1234567890"); return t; } int main() { char *t1 = NULL; Test1(t1); printf("nTest1: %sn", t1); char *t2 = NULL; Test2(&t2); printf("nTest2: %sn", t2); char *t3 = (char *)malloc(11); Test3(t3); printf("nTest3: %sn", t3); char *t4 = NULL; t4 = Test4(t4); printf("nTest4: %sn", t4); return 0; }
gives this output:
Test1: (null) Test2: 1234567890 Test3: 1234567890 Test4: 1234567890
What's wrong with Test1 function? And why Test4, which almost similar to Test1, works? More general question: what's the correct way to create string in function and return pointer to it?
Consider your Test1 performs the following behavior:
char * x1 = NULL;
Test1 (x1);
Test1 is done within the following:
void test1 (char * t) / / t -> x1 -> null
{
t = (char *) malloc (11);
// t now points a different place (the memory allocated), and the reference of x1 continues pointing to null
strcpy (t, "1234567890"); // t value is "1234567890" but x1 continues pointing to null
// Error, the memory that is pointed by t is never released
}
printf ("nTest1:%s n", t1); / / Print the value of x1 (null) and the reference of t is lost
The function parameters aren't working the way you think. You're passing in the value by "value" rather than by "reference" which means once inside the function, any changes to those values are local only to that function, so when the function exits the local changes are thrown away.
To fix this, either pass in a pointer to the pointer (char** t), or pass the pointer by reference (char&*) and change the function code to match.
you have defined t1 as char* t1 = NULL;
and calling the function as Test1(t1);
passing the pointer variable t1 (not its address).
The function Test1 is expecting a char* void Test1(char *t)
here t
is a variable local to Test1
function only. Any modification that you do inside the function will not be visible out side the function because you are actually not modifying the main
function's variable t1
but the local variable t
.
上一篇: 使用va调用printf
下一篇: 指向函数中的字符串