简体   繁体   中英

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:

char *myvar = "";
f(myvar);
// others operation;
free(myvar);

My question is it correct assign a const as "" to a char pointer as myvar ? If not, how can I do it?

The function f() is doomed. Its effect on var cannot be seen outside its scope.

It should be changed so that either:

(i) it receives a preallocated buffer:

void f(char *var) {
  // just uses var contents
}

(ii) it receives a pointer to a buffer where it can store a new allocated area:

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):

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 . 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 .

If you call it like 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() .

Also, that call should not have its return value cast, in C .

Trying to understand the purpose of your code, the myvar = "" initialization seems pointless.

In function f , you are setting the local variable var to some value. 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);
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM