int main() { const int marbles[10] = { 1,2,3,4,5,6,7,8,9,10 }; in...">

Why is my data not protected, even if I use "const" in C?

#include <stdio.h>

int main() 
{
    const int marbles[10] = { 1,2,3,4,5,6,7,8,9,10 };
    int *ptr = marbles;
    *ptr = 100;
    printf("%d \n", marbles[0]); // output is "100"

}

I used constto protect the array. So I thought that int *ptr = marbleswould cause an error. Otherwise, using a pointer, it will allow the user to modify the data in the array. But surprisingly, the output is "100". Shouldn't C protect the array from any methods when I use const?

+4
source share
2 answers

When I tried to compile the program, it showed this warning. Therefore, I assume that when the pointer is initialized, the keyword constloses effect.

In function β€˜main’:
try.c:6:16: warning: **initialization discards β€˜const’ qualifier from pointer** target type [enabled by default]
     int *ptr = marbles;
+3
source

, , int *ptr = marbles .

"". C- , "".

, .

, , , , "" .

+2

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


All Articles