machine_1
machine_1

Reputation: 4454

Can we return pointer to new static array from the same function?

Is there a way to return a new array allocated with the static keyword after each invocation of a function? I can create a new array if i make a clone to the function, but not from the same function.

Consider the following program:

#include <stdio.h>

char *CrArray1(void);
char *CrArray2(void);

int main(void)
{
    char *p1 = CrArray1();
    strcpy(p1, "Hello, ");

    char *p2 = CrArray1();
    strcat(p2, "World");

    char *q1 = CrArray2();
    strcpy(q1, "Different String");

    printf("p1 is : %s\n", p1);
    printf("q1 is : %s\n", q1);

    return 0;
}

char *CrArray1(void)
{
    static char Array[128];
    return Array;
}

char *CrArray2(void)
{
    static char Array[128];
    return Array;
}

Upvotes: 3

Views: 174

Answers (3)

Jesse Chen
Jesse Chen

Reputation: 529

No, we can't.

wikipedia:

static is used to store the variable in the statically allocated memory instead of the automatically allocated memory.

so if you add after q1:

char *q2 = CrArray2();
strcpy(q2, "Another String");

and print q2, you will get:

p1 is : Hello, World q1 is : Another String q2 is : Another String

That means the local static variable still points to the same memory. So the result is not we want.

But if you use the malloc to require a new memory in function. Each time the pointer that function returned will point to different memory. so there is no influence of those variables.

More about static you can refer what does static means in a C program

Upvotes: 0

sameerkn
sameerkn

Reputation: 2259

If at compile time you know how many times you are going to call the function then following can be used:

#define NUMBER_OF_TIMES_FUNCTION_WILL_BE_CALLED 10
char *CrArray1(void)
{
    static int i = -1;
    static char Array[NUMBER_OF_TIMES_FUNCTION_WILL_BE_CALLED][128];
    ++i;
    return Array[i];
}

Note: NUMBER_OF_TIMES_FUNCTION_WILL_BE_CALLED has to be a reasonable number.

Upvotes: 1

Kornel
Kornel

Reputation: 100120

No, static objects by definition have only one instance.

You'll need to use malloc() and callers of your function will need to free() the memory.

Upvotes: 1

Related Questions