Search code examples
carraysconstantsmemory-addressmutable

Can you declare an array with constant address but mutable elements?


The C Programming Language

It is not uncommon to define constant pointers to non constant (i.e., mutable) values. So if you do not expect an array to move, but its content to change:

  1. Can you define an array with constant (const) address, but mutable elements?
  2. If yes, then how?

Solution

  • That defines all arrays of non-constant elements. Once an array have been created, it's in a fixed location.

    If you want an array of constant pointers (who can't point to any other values other than what has been used to initialize them) who point to mutable values then (perhaps) use this:

    #include <stdio.h>
    
    int main(void) 
    {
        int i=0;
        int j=9;
        int *const ptr[2]={&i,&j};
        *ptr[0]=3;
        printf("%d %d",*ptr[0],*ptr[1]);
        return 0;
    }
    

    OUTPUT: 3 9