Defining a dynamic, read-only array in C

Viewed 541

How do I define a dynamic read-only integer array in C?

I know that we can allocate static read-only array by using the qualifiers, 'const' and 'static'. But how to do the same in the case of a dynamic array?

2 Answers

There isn't any standard way to define dynamically allocated memory as const. There wouldn't be much point since you cannot use initialisation for dynamically allocated memory other than calloc to initialise it to zero. C simply doesn't have any standard library functions for initialising the memory to anything else. It requires you to use assignment instead, which would never work with const.

You can declare a pointer to dynamically allocated memory as const, but if you do this, users are permitted (as far as the language standard is concerned) to cast away the const and modify the data anyway.

In theory that might not be good enough, but in practice it is. Code which casts away const to modify data, especially in ways not clear to the caller, is very uncommon.

You can use the const qualifier to point to an already created non const array:

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

int *alloc(int n)
{
    int *arr = malloc(n * sizeof(*arr));

    for (int i = 0; i < n; i++) {
        arr[i] = i;
    }
    return arr;
}

int main(void)
{
    const int *arr = alloc(5);

    arr[3] = 5; /* error */
    return 0;
}
Related