0

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user1138143
  • 81
  • 1
  • 12

2 Answers2

1

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

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You can use a static local variable like this:

static abc* xyz(int a){
  static abc z;
  return &z;
}
technosaurus
  • 7,676
  • 1
  • 30
  • 52
Nghia Bui
  • 3,694
  • 14
  • 21