Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 434
machine_1 Avatar asked Dec 11 '25 06:12

machine_1


1 Answers

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.

like image 119
Kornel Avatar answered Dec 12 '25 19:12

Kornel