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?
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;