[英]Passing to pointer to char in function and read value in caller
I want to pass pointer to a function which pass this pointer to another function which points to the array and after this function end I want read the value in the caller function. 我想将指针传递给一个函数,该指针将该指针传递给另一个指向数组的函数,并且在此函数结束后,我想读取调用函数中的值。
So this is the example code how I want it to work: 所以这是示例代码,我希望它如何工作:
void fun_1(const char *data)
{
/* some code */
fun_2(data);
}
void fun_2(const char *data)
{
/* some code */
fun_3(data);
}
static bool fun_3(const char *data)
{
static char buffer[20];
/* some code */
data = buffer;
return true;
}
And to function fun_1 I want pass static char *resp and after fun_3 end I want to have address of buffer and then read out from it but now when fun_3 ends the resp is always NULL. 而要使fun_1功能,我想传递静态char * resp,并在fun_3结束后我想要具有缓冲区的地址,然后从中读出,但是现在fun_3结束时,resp始终为NULL。
C is pass by value. C是按值传递。 Assigning to a local variable inside a function is transient, the effect will not pass to the caller's parameter variable. 分配给函数内部的局部变量是瞬时的,效果不会传递给调用者的参数变量。
In your case I suspect you don't want to use assignment but rather strcpy
or memcpy
to copy the buffer into a buffer provided by the calling code. 在您的情况下,我怀疑您不想使用分配,而是使用strcpy
或memcpy
将缓冲区复制到调用代码提供的缓冲区中。
Be careful that the calling code allocates a sufficiently large buffer though, and make the caller pass in the buffer size to avoid overriding the available space: 但是请注意,调用代码会分配足够大的缓冲区,并让调用者传递缓冲区大小,以免覆盖可用空间:
static bool fun_3(const char *data, size_t size) {
char buffer[20];
if (size < sizeof buffer) return false;
/* some code */
memcpy(data, buffer, sizeof buffer);
return true;
}
char buffer[25];
bool success = fun_3(buffer, sizeof buffer);
Alternatively, if you really want to return a pointer to a local static variable (but think carefully about the implications! In particular thread safety), you can either 或者,如果您确实要返回指向局部静态变量的指针(但请仔细考虑其含义!尤其是线程安全性),则可以
return the pointer: 返回指针:
char *fun_3() { static char buffer[20]; /* some code */ return buffer; }
char *buffer = fun_3();
pass by pointer: 通过指针传递:
static bool fun_3(const char **data) { static char buffer[20]; /* some code */ *data = buffer; return true; }
char* buffer; bool result = fun_3(&buffer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.