1

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?
Klorax
  • 579
  • 2
  • 6
  • 10
  • 4
    That defines *all* arrays of non-constant elements. Once an array have been created, it's in a fixed location. – Some programmer dude Sep 15 '18 at 19:48
  • 1
    Short answer: pointers (to which you can assign an address) and arrays (to which you *cannot* assign an address) can often be used interchangeably. To answer your question: perhaps a const pointer might be a good solution. Look here for more details: https://stackoverflow.com/questions/1143262/ – paulsm4 Sep 15 '18 at 19:49
  • 2
    Klorax, `int a[42];` is an example of "an array with constant (const) address, but mutable elements". What do you want that is different from that? – chux - Reinstate Monica Sep 15 '18 at 19:55

1 Answers1

3

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

Klorax
  • 579
  • 2
  • 6
  • 10
Gaurav
  • 1,570
  • 5
  • 17