在方法内初始化char指针

时间:2015-01-29 23:47:36

标签: c arrays pointers char

我想将char指针作为参数传递给像这样的函数:

void foo(char* array_of_c_str[], const int size_of_array, char* result_ptr)
{
     // my logic

     result_ptr = a[n];
}

并且这样打电话:

char* result_pointer = NULL;
foo(array_of_c_strings, 5, result_pointer);
printf("%s", result_pointer); // here result_pointer is always null

我想初始化函数内部的char指针,当调试一切正常时,但是当离开函数的范围时,这个指针再次变为null,即使它离开函数的范围,如何保持初始化?

1 个答案:

答案 0 :(得分:6)

您无法更改传递给函数的值。

result_ptr更改为char**,然后将目标指针的地址传递给该函数:

// Now a double pointer ---------------------------------------v
void foo(char* array_of_c_str[], const int size_of_array, char** result_ptr)
{
     // my logic

     // Note the addition of the * at the front - we want to modify
     // the char* whose address was passed to us.
     *result_ptr = a[n];
}

并且这样打电话:

char* result_pointer = NULL;

// Pass the address of your pointer:
//                  -------v
foo(array_of_c_strings, 5, &result_pointer);
printf("%s", result_pointer);