简体   繁体   中英

How to make the struct pointer point to a static char array

In the below piece of code, function returns an uninitialized pointer.

static abc* xyz(int a)                
{
    abc *z; 
    return(z);
}

How to modify this function, so that this pointer point to a static char array. Any suggestion please.

If I understood your question ( little weird, IMHO ) correctly, what you want is something like ( with VLA support )

static abc* xyz(int a)      //int a is unused here              
{
    abc *z = NULL; 
    static char buf[sizeof(abc)];  //static char array

    z = abc;

    return z;
}

NOTE: FWIW, the static is not the "storage class" for function return type or value. It does not mean that the function has to have a static variable as the expression with return statement.

Rather, this is the part of the function definition ( declaration-specifiers , to be precise), to indicate that the function has internal llinkgae. In other words, the visibility of the function is limited to that particular translation unit only.

Related, from C11 , chapter §6.9.1, Function definitions Syntax

function-definition:
declaration-specifiers declarator declaration-list opt compound-statement

and

The storage-class specifier, if any, in the declaration specifiers shall be either extern or static .

then, chapter §6.2.2, paragraph 3,

If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static , the identifier has internal linkage.

If the above note makes sense, this related answer will also do, maybe in a better way

After this note, I think you would like to have a corrected version of the previous code, which looks like,

static abc* xyz(int a)      //int a is unused here              
{
    abc *z = NULL;
     //some code
    z = malloc(sizeof(*z)); //sanity check TODO
     //some more code
    return z;
}

only thing, you need to free() the returned pointer once you're done using it.

You can use a static local variable like this:

static abc* xyz(int a){
  static abc z;
  return &z;
}

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