指向函数中的字符串

clu*_*ter 5 c string memory-management

似乎我坚持一些基础知识.有人可以解释我为什么下一个代码:

#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几乎相似?更一般的问题:在函数中创建字符串并返回指针的正确方法是什么?

小智 7

功能参数不按您的想法运行.您通过"值"而不是"引用"传递值,这意味着一旦进入函数,对这些值的任何更改都只对该函数是本地的,因此当函数退出时,本地更改将被丢弃.

要解决这个问题,要么传入指向指针的指针(char**t),要么通过引用传递指针(char&*)并更改功能代码以匹配.


xla*_*rsx 0

考虑您的 Test1 执行以下行为:

char * x1 = NULL;
Test1 (x1);
Run Code Online (Sandbox Code Playgroud)

Test1 在以下范围内完成:

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
}
Run Code Online (Sandbox Code Playgroud)
printf ("\nTest1:%s \n", t1); / / Print the value of x1 (null) and the reference of t is lost
Run Code Online (Sandbox Code Playgroud)