看来我是被卡住了一些基础知识。有人可以解释我为什么下面的代码:指针,指向函数的字符串
#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; }
给出了这样的输出:
Test1: (null) Test2: 1234567890 Test3: 1234567890 Test4: 1234567890
这有什么错Test1的功能?为什么Test4与Test1几乎相似? 更一般的问题:在函数中创建字符串并返回指针的正确方法是什么?
您已经标记了C++和C,而这取决于在C++中,你应该使用`std :: string`(除非有一些迫切需要!),在C中,除了第一种方法都是可能的。 – Nim 2011-01-07 14:52:33
是的,我可以使用字符串类,但我想了解核心,这就是为什么我在这里使用char *。 – clumpter 2011-01-07 15:46:23
在C中,do * NOT *强制转换了`malloc()`的结果。在这里阅读推理:http://stackoverflow.com/a/605858/1701799(基本上,这是因为一个`void *`会自动安全地升级到适当的类型)。我知道这被标记为C/C++,但没有这样的语言“C/C++”。如果这是C++,那么您将使用`#include`而不是`#include `。我认为这应该只是被标记为C.在C++中,你几乎不会使用`malloc()```free()`,而是使用`new/delete`,或者更好的智能指针/ etc .. –
RastaJedi
2016-02-22 05:35:12