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: %s\n", t1); char *t2 = NULL; Test2(&t2); printf("\nTest2: %s\n", t2); char *t3 = (char *)malloc(11); Test3(t3); printf("\nTest3: %s\n", t3); char *t4 = NULL; t4 = Test4(t4); printf("\nTest4: %s\n", 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?
std::string
(unless there is some pressing need not to!), in C, all except the first approach is possible. – Nimmalloc()
. Read here for reasoning: stackoverflow.com/a/605858/1701799 (basically it's because avoid *
will be automatically and safely promoted to the appropriate type). I know this is tagged as C/C++, but there is no such language "C/C++". IF this was C++, you would be using#include <cstdlib>
and not#include <stdlib.h>
. I think this should probably just be tagged C. In C++, you would pretty much never usemalloc()
/free()
but instead would usenew/delete
, or even better, smart pointers/etc.. – RastaJedi