0

I'm trying to increase a static array by doubling it dynamically in another array as soon as it is maxed. I planed on created new array with malloc(), then copy values over. Once done, I planned on deleting first array and then pointing first pointer to second?

float FirstArray[1];

if (first array is full) {
    float *TempArray = (float*) malloc (sizeof (float) * counter);
    for (loop) {
        TempArray[i] = FirstArray[i];
    }
    //I'm not sure how to point the static array to the dynamic one
    free(FirstArray);
    *FirstArray = &TempArray;
//i get this error with line above
//assignment makes integer from pointer without a cast
}    
1
  • That's ok, but FirstArray needs to be dynamically allocated initially also. Commented Mar 3, 2012 at 23:13

3 Answers 3

4

Perhaps you should consider realloc, as this is exactly why it exists.

Sign up to request clarification or add additional context in comments.

Comments

1

FirstArray needs to be dynamically allocated as well:

int counter = 1;
float *FirstArray = (float *)malloc(sizeof(float)*counter);

if (first array is full) {
float *TempArray = (float*) malloc (sizeof (float) * counter);
for (loop) {
TempArray[i] = FirstArray[i];
}
free(FirstArray);
FirstArray = TempArray;

Comments

0

Static array allocations are managed automatically: you do not need to (and should not) allocate it, so you should not free it as well. You cannot assign a float * (pointer) to float[N] (N-elem static array) because these are considered incompatible types by the compiler. (Static array is also zeroed on init to mention one more difference.)

So basically you have two choices: forget the name FirstArray, preserve its content under new name (SecondArray?). Nonsense.. Other way is to have dynamic array from the beginnings.

uint size = 4096;
double * array = ( double * ) malloc( sizeof( double ) * size );

Then copy could be unneccessary, so use realloc as Richard and Oliver pointed out.

size <<= 1; /* double size */
array = ( double * ) realloc( ( void * ) array, sizeof( double ) * size );

Notice that input and output pointers of realloc might differ. If not, copy is spared.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.