Skip to main content
gamedev.net
🔒 Locked

variable-size array

Started by LongJohn 3 replies 250+ views
Original Post
LongJohn
LongJohn
hi, i´m getting the compiler warning: textureloader.h:89: warning: ISO C++ forbids variable-size array ` even if it does compile well,i´m,k wondering what to do if i can´t now the array size in advance ? the code looks like: long DataSizeJustCalculated = someSimpleMaths usigned char data[DataSizeJustCalculated] any thoughs ?
billybob
billybob
unsigned char * data = new unsigned char[DataSizeJustCalculated];

but you have to delete it later or you''ll get a memory leak:

delete [] data;
Null and Void
Null and Void
Pre- and Post-C99 C:

#include <stdio.h>
#include <stdlib.h>

int Size = 10;

int main(void) {
/* Allocate Size integers, and point Array at them */
int *Array = (int *) malloc(sizeof(int) * Size);

if(Array == NULL) {
puts("Error allocating memory");
return -1;
}

/* You MUST call this when you''re done with the allocated
memory. Afterwards, you can NOT use what Array is pointing
at. */
free(Array);

return 0;
}

C++:

int Size = 10;

int main(void) {
// Allocate an array of Size integers, and point Array at them.
// new will throw an exception if it fails by default
int *Array = new int[Size];

// You MUST call this when you''re done with the allocated
// memory. Afterwards, you can NOT use what Array is pointing
// at.
delete [] Array;

return 0;
}

More C++:

#include <vector>

int main(void) {
// Allocate an array of Size integers within Array
std::vector <int> Array(10);

return 0;
}


Null and Void
Null and Void
I used to be quicker before I started getting errors twelve times before I posted .

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.