helloc
helloc

Reputation: 23

Creating a C function that initialises a struct and returns back a pointer

I'm learning C and i'm trying to do the following:

typedef of table: typedef char table [8][8];

So, I created this function:

table* create_table() {
  table o;
  return &o;
}

But i get an error from compiler saying that I'm returning address of a local variable.

How do I do t o create a table from the function and then return the pointer.

Upvotes: 2

Views: 143

Answers (2)

MByD
MByD

Reputation: 137382

You cannot give back the address of a local variable, as the address become invalid one the function (create_table) returns, instead, you should create it on the heap:

table* create_table() 
{
    table * o;
    o = malloc(sizeof(table));
    // Edit - added initialization if allocation succeeded.
    if (o != NULL)
    {
        memset(o, 0, sizeof(table));
    }
    return o;
}

Upvotes: 8

sashang
sashang

Reputation: 12214

You can't return the address of a local variable. It is deallocted when the function exits. You have to allocate it using malloc and return that pointer. For example:

table* ptr = malloc(sizeof(table));
memset(ptr, 0, sizeof(table));
return table;

Upvotes: 2

Related Questions