[英]Assign a const to char pointer on initialization
I Have a function that I cannot change like: 我有一个无法更改的功能,例如:
void f(char *var) {
var = (char*) malloc(size*sizeof(char)); // I dont know the size, its a example
// .. others operation with var
}
So whats the best way to initialize a variable using f
function: 那么使用
f
函数初始化变量的最佳方法是什么:
char *myvar = "";
f(myvar);
// others operation;
free(myvar);
My question is it correct assign a const
as ""
to a char
pointer as myvar
? 我的问题是正确的,将一个
const
作为""
分配给一个char
指针作为myvar
吗? If not, how can I do it? 如果没有,我该怎么办?
The function f()
is doomed. 函数
f()
注定了。 Its effect on var
cannot be seen outside its scope. 它对
var
影响无法超出其范围。
It should be changed so that either: 应该更改它,以便:
(i) it receives a preallocated buffer: (i)收到预分配的缓冲区:
void f(char *var) {
// just uses var contents
}
(ii) it receives a pointer to a buffer where it can store a new allocated area: (ii)它收到一个指向缓冲区的指针,该缓冲区可以存储新分配的区域:
void f(char **var) {
*var = (char*) malloc(size*sizeof(char));
// .. others operation with var
}
or 要么
(iii) it returns the newly allocated buffer (in this case the argument is useless): (iii)返回新分配的缓冲区(在这种情况下,该参数无用):
char* f(char *var) {
var = (char*) malloc(size*sizeof(char)); // I dont know the size, its a example
// .. others operation with var
return var;
}
These 3 options would give usable semantics to the function f
. 这三个选项将为函数
f
提供可用的语义。 But as you said you cannot change it, then it's doomed. 但是正如您所说的,您无法更改它,那么它就注定了。
What? 什么?
If the function looks like that, and you can't change it, you can't do what you seem to want to do. 如果该函数看起来像这样,并且您无法更改它,那么您将无法做您想做的事情。
The function can't change the value of a variable in the caller's scope, that's simply not possible without making the argument be char **var
. 该函数无法在调用者的作用域内更改变量的值,这是不可能的,除非将参数设为
char **var
。
If you call it like f("");
如果您像
f("");
这样称呼它f("");
it will be called with the address of some static string somewhere, but that address will immediately be overwritten by the call to malloc()
. 它将使用某个静态字符串的地址在某处进行调用,但是该地址将立即被
malloc()
的调用所覆盖。
Also, that call should not have its return value cast, in C . 同样,该调用不应将其返回值转换为C。
Trying to understand the purpose of your code, the myvar = ""
initialization seems pointless. 为了理解代码的目的,
myvar = ""
初始化似乎毫无意义。
In function f
, you are setting the local variable var
to some value. 在函数
f
,您正在将局部变量var
设置为某个值。 This will have no impact on the value of the variable that you pass to this function when you call it. 这将对调用该函数时传递给该函数的变量的值没有影响。 Change it to any one of the following options:
将其更改为以下任一选项:
void f(char** var,int size)
{
*var = malloc(size);
...
}
void SomeOtherFunc()
{
char* myvar;
...
f(&myvar,size);
...
free(myvar);
...
}
char* f(int size)
{
char* var = malloc(size);
...
return var;
}
void SomeOtherFunc()
{
char* myvar;
...
myvar = f(size);
...
free(myvar);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.