So I read somewhere, that declaring string like:
char * string="someString";
should not be used and instead we should use following:
const char* string = "someString";
I am not sure why is this a better approach, as I cannot change string declared in a second way.
Moreover I never experienced any problem, when I used simple:
char string[] = "someString";
and I used following, when I wanted string to be constant:
const char string[] = "someString";
So i wrote a simple program in order to see what is happening underhood:
#include <stdio.h>
int main(void)
{
const char* someString = "someString";
char anotherString[] = "someString1";
char* yetAnotherString = "someString2";
const char yetyetAnotherString[] = "somestring3";
printf("someString pointer = %p\n", someString);
printf("anotherString = %p\n", anotherString);
printf("yetAnotherString pointer = %p\n", yetAnotherString);
printf("yetyetAnotherString = %p\n", yetyetAnotherString);
return 0;
}
What I got was:
someString pointer = 000000013F2870B0
anotherString = 000000000017FD50
yetAnotherString pointer = 000000013F2870D0 //next to someString pointer
yetyetAnotherString = 000000000017FD60// next to anotherString
That would suggest that strings declared with pointers explicitly are in completely different memory space than ones declared with table syntax, although as we know tables are just normal pointers.
I searched a bit on the Internet about this and found out that the first and the third approach can allocate strings in a code segment, while others allocate it on the stack, that would explain why we should not declare strings with
char * string = "xyz";
As it will "allow" us to change data in code segment, which should not be allowed.
That's how far I managed to understand all these things but I cannot find answer on the following:
Why is the compiler allowed to allocate strings (in this case) in the code segment if I said explicitly that later on I want to be able to change value, where the pointer is pointing? Compiler should know this, so why is it doing it? How does compiler know what to do if I use table syntax if both in fact simply declare pointers?