Your question exhibits one of the several reasons why global variables are generally ill-advised. The generic (i.e. not OS specific) solution is to make the array static and hidden within a translation unit (i.e. not global) with public access functions which can then conditionally provide write access and also bounds-checking.
For example:
Array.c
#include <stdbool.h>
static int array[100] ;
static bool protected = false ;
int read_array( unsigned index )
{
return array[index] ;
}
void protect_array()
{
protected = true ;
}
void unprotect_array()
{
protected = false ;
}
void write_array( unsigned index, int value )
{
if( !protected && index < sizeof(array) )
{
array[index] = value ;
}
}
size_t sizeof_array()
{
return sizeof(array) ;
}
size_t lengthof_array()
{
return sizeof(array) / sizeof(*array) ;
}
That provides global control of read/write access (i.e. at any time the array is either R/W or R/O. It may be that you want to simultaneously provide read/write access to some users and read-only to others. That can be achieved thus:
Array.c
static int array[100] ;
int* get_array_rw()
{
return array ;
}
const int* get_array_ro()
{
return array ;
}
size_t sizeof_array()
{
return sizeof(array) ;
}
size_t lengthof_array()
{
return sizeof(array) / sizeof(*array) ;
}
This method will catch write access attempts via the read-only pointer at compile time. However it still has most of the problems associated with global variables.
A less generic OS specific method is to use a memory-mapped file for the array and use the access control for the memory-mapped file to impose read-only or read-write semantics:
size_t array_len = 100 ;
int fd = open( "arrayfile", O_RDONLY, 0);
if( fd >= 0 )
{
int* array = mmap( NULL, array_len * sizeof(int), PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
// Now array points to read only memory
// accessible through normal pointer and array index operations.
}
A further method, but not within the scope of your question is to use C++ and wrap the array in a class and use operator overloading of [] to access the array. This method is identical to the first suggestion, but syntactically allows array-like access like the second and third.