What is an array of constant pointers in C?

Is the address of the array, and therefore all of its elements, constant?

And if so, in an ad like:

char *const argv[] 

not a redundant qualifier const?

+4
source share
3 answers

No.

Firstly, const“constant” is actually two different things in C, although the keyword is constobviously derived from the word “constant”. A constant expression is an expression that can be evaluated at compile time. constreally means read-only. For example:

const int r = rand();

is completely legal.

, - - . , ( ) , , , .

:

char *arr1[10];
char *const arr2[10];
const char *arr3[10];

arr1 - 10- char. char*, , .

arr2 - const ( ) char. , char* ( ), char, .

arr3 - const char; , , .

, argv, , main, . , main

char *argv[]

, ,

char **argv

const. , , , , . (: , argv getopt(), char * const argv[].)

, , : , , "" . ( .) . .

C - . , .

6 comp.lang.c FAQ .

+5

, . char *const argv[] - char. , const ( , ).

+2

, , ?

, C. , , . , . .

int a = 4;
a = 6;  // legal. you can change the value of the object
&a = 23456; // illegal. you cannot change the address of the object

, , . , , .

, ,

char *const argv[]
char *const *argv

, argv , char *const, . , char *const *argv char **argv . .

char *const argv[10];

argv 10 . , , . .

char c = 'A';
char d = 'B';
char *const argv[2] = {&c, &d}; 

argv = &c; // illegal. you cannot the change the address of an object
argv[0] = &d; // illegal. you cannot change the value of the array element
*argv[0] = 'C'; // legal. you change the value pointed to by the element

Without a qualifier const char *argv[2]means an array of pointers 2for characters. This is clearly different from the case when we have a qualifier const, as explained above. Therefore, to answer your second question, no, constit is not redundant. This is because the qualifier constqualifies the type of array elements.

+2
source

Source: https://habr.com/ru/post/1534264/


All Articles