修改函数中的指针

时间:2019-05-07 12:50:25

标签: c pointers dynamic-memory-allocation pass-by-value

我做了一个允许通过键盘输入字符串的函数。该函数有两个参数:字符串的最大可能长度和指向char的指针。函数内部发生的事情是,声明了一个字符数组,该数组具有与最大长度一样多的元素,然后将用户给出的字符串临时存储在该数组中。字符串的获取完成后,我将使用calloc函数分配适当的内存,以将相同的字符串存储在作为参数传递的char指针中。

int main(void)
{
    char* test;

    stringInput(test, 10);

    printf("%s", test);

    return 0;
}

void stringInput(char* string, int maxStringLength)
{
    char tempString[maxStringLength];

        //STRING GETS PROPERLY STORED IN tempString

    string = (char*)calloc(strlen(tempString)+ 1, sizeof(char));

    strcpy(string, tempString);

    return;
}

这是一种工作,这意味着如果我尝试在此函数击中return之前打印“ string”,则程序实际上将显示其预期内容。但是,当我尝试在主函数中打印“ test”时,它什么也没打印,这意味着stringInput并没有修改传递给它的指针。我通过在函数调用之前,calloc行之后以及函数调用之后再次打印“ test”的地址来进一步确认这一点,这表明在calloc之后它发生了变化,但在函数调用时又返回其先前的值结束。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

这里的问题是test本身是通过值传递的,该值存储在string中,而您对string所做的任何更改都不会反映回test

如果要修改test本身,则需要传递指向test的指针。

类似

 stringInput(&test, 10);

void stringInput(char** string, int maxStringLength)
{
    char tempString[maxStringLength];

        //STRING GETS PROPERLY STORED IN tempString

    *string = calloc(strlen(tempString)+ 1, sizeof(char));  // no need to cast
    if (!string) {
       printf("error in calloc!!\n");
       return;
     }
    strcpy(*string, tempString);

    return;
}

答案 1 :(得分:2)

calloc string插入string时,仅修改test的本地副本,而不修改void stringInput(char **string_p, int maxStringLength) 变量。您可能想要做的就是传入并在指向char指针的指针上进行操作。

您可以将功能签名更改为:

string

然后,将*string的用法替换为test

最后,您将调用函数,并传递指向stringInput(&test, 10); 的指针,而不是指向其值的指针:

{{1}}

这是一种处理方式,尽管您也可以根据构造方式返回一个指针。