Abhi Abhi - 3 months ago 12
C++ Question

Is there any significance of having a static keyword for a dynamically created array?

I am allowed to execute this code without an error. So I believe C++ allows this.

char *foo (char *start, int n) {
static char* temp; //Does this have any significance?
temp = new char[n];
for (int j=0; j<n; j++)
return temp;

int main(){
char *c;
char a[6]={'1','2','3','4','5','\0'};
c = a;
int n = sizeof(a);
c = foo(c,n);
delete []c; //Does this delete the static array created in foo()?
return 0;

P.S.- I know there is a better way of reversing an array but the Q is not focused on that. I just was not able to come up with a better example.:)

EDIT: I understand temp gets created in heap and I don't need to use static. But does static keyword in variable declaration make any difference while creating a dynamic array in memory mapping, etc.?

Answer Source

The temp variable is static, the memory block whose address it stores is dynamically allocated (new char[n]) and freed (delete []c).

They are different objects.

The array doesn't care about temp (it doesn't even know about it). You can store the address of the array in many variables; this doesn't change its behaviour in any way.

I understand temp gets created in heap.

temp is not created in the heap. It is a local variable; local variables are not stored in the heap.

   static char* temp; //Does this have any significance?

The static keyword makes temp a permanent variable, that exists since the program starts until it ends. The static keyword ensures its value is not lost when the function ends. Every time the function foo() is executed (except the first one), the value of temp is the same it was the last time when it ran.

But, being a local variable, temp is available only in the foo() function.

The value of temp is a memory address. The address of the block allocated using new char[n]. This block of memory is allocated in the heap and it is valid until it is released (using delete []c). It can be accessed from main() too, given its address is somehow available in the main() function. And it is available because the call to the foo() function returns it and main() stores it in c.

    delete []c; //Does this delete the static array created in foo()?

No, it deletes (in fact, releases) only the array (created in foo()). The static variable (temp) is not affected in any way.