If you don't malloc
memory before trying to access your array, then your pointer will probably corrupt random addresses in memory.
So first thing to do:
#define ARRAY_LENGTH 10 // 10 Bytes
int main()
{
char *char_arr;
// Initial memory allocation
char_arr = (char *) malloc(ARRAY_LENGTH);
// [Do stuff]
free(char_arr); // Don't forget to free!!!!
return(0);
}
Then if you want to want to access your array using another type you must not break the strict aliasing rule.
And as @atturri said pointer arithmetic is illegal with void pointers.
So you have to use a new pointer to access your array using an other type. And you have to take care of the upper bound of your new array:
int *int_array = (int*) char_arr;
int elementsCount = sizeof(*int_array) / sizeof(*char_arr);
for (int i = 0; i < elementsCount ; i++)
{
int_array[i] = i;
}
Finally:
#define ARRAY_LENGTH 10 // 10 Bytes
int main()
{
char *char_arr;
int *int_array = (int*) char_arr;
int elementsCount = sizeof(*int_array) / sizeof(*char_arr);
int i;
// Initial memory allocation
char_arr = (char *) malloc(ARRAY_LENGTH);
// Do stuff
for (i = 0; i < elementsCount ; i++)
{
int_array[i] = i*2;
printf("int_array[%d]=%d", i, int_array[i]);
}
free(char_arr);
/* Don't forget to free!! (Even if it's not "dangerous"
* in this example in the main since we are about to quit */
return(0);
}