In C, I know I can make an array like this
int myarray[5] = {a,b,c,d,e};
However, imagine the array was already initialised like
Here is a solution that is all standards compatible (C89, C99, C++)
It has the advantage that you only worry about entering the data in one place. None of the other code needs to change - there are no magic numbers. Array is declared on the heap. The data table is declared const.
(Click here to try running it in Codepad)
#include
#include
int main()
{
unsigned int i = 0;
int *myarray = 0;
static const int MYDATA[] = {11, 22, 33, 44, 55};
myarray = (int*)malloc(sizeof(MYDATA));
memcpy(myarray, MYDATA, sizeof(MYDATA));
for(i = 0; i < sizeof(MYDATA)/sizeof(*MYDATA); ++i)
{
printf("%i\n", myarray[i]);
}
free(myarray);
return 0;
}