Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi!
Now that I'm (at last) starting to deal better with vc++, I go back to more fundamental problems.
I have a function (member of a class, but whatever) dealing with an array. I would like, in this function, to have a memory that keeps track of the array as it was in the last call of the function.
Typically, if my variable had been an int, i would have declared a static int in the function, and saved the old value in that variable.
But when it comes to an array, it does not work anymore! i tried:static int arr[CONST];
But that does not seem to work (I guess that the static refers to a pointer to int, or some strange stuff related to how is declared an array in c++).
Someone who knows how I can tell my computer to consider the CONTENT of the array as static?
Thanks a lot for any help!

The definition that you show is correct and should work. It doesn't matter if it's an array or a scalar variable. Possibly VC++ doesn't implement this correctly, but I doubt that is the problem.
Try the following program to see if it works for you in VC++ (I ran it on a linux box and you can see the ouptut below).
#include stdio.h
#define CONST 5
void myfunc(int);
void main(void) {
myfunc(2);
myfunc(5);
}
void myfunc(int increment) {
static int arr[CONST];
int i;printf("BEFORE: ");
for (i=0; iprintf("%d ",arr[i]);
}
printf("\n");
for (i=0; iarr[i] += increment;
}printf("\n\nAFTER: ");
for (i=0; iprintf("%d ",arr[i]);
}
printf("\n\n\n");}
OUTPUT:
BEFORE: 0 0 0 0 0
AFTER: 2 2 2 2 2
BEFORE: 2 2 2 2 2
AFTER: 7 7 7 7 7

As you may have expected, you're perfectly right.
And I also found why it was not working (I fell quite ridicullous about it, by the way)...
I had several calls (say : call A, call B, call C, call D) to that function in a loop. I was stupidly expecting the function to keep a memory of an array (in a static int[]), and that the memory saved in the call A would be kept until the next call A.
Which is obviously not really clever, for the other calls overwrote it.
Now I did it in a cleaner way.
And I achieved what I wanted to.
Thanks a lot!

Also remember, that your Class may have more than one instance, but all of them write to the same static memory. Use a class member for cleaner code. You can also make class members static, even function members.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |