What is the difference between "chars[]" and "char*s"?

Asked 2 years ago, Updated 2 years ago, 159 views

In C, when saving a string,

There are two ways together. What's the difference between these two? I want to know what actually happens on memory when I compile, when I run.

c string char constant

2022-09-22 22:22

1 Answers

char *s = "Hello world"; writes "Hello world" in the read-only portion of memory, and s points to that location. You can no longer write anything else to this memory area.

int main(){
    char *s = "Hello World";
    s[0] = "h"; // Trying to write read-only. Error!
    printf("%s", s);
}

chars[] = "Hello world"; places "Hello world" in the read-only area of memory and copies this string to the stack. The stack area is easier to modify than the former because it is a usable part.

int main(){
    char s[] = "Hello World";
    s[0] = "h"; // possible
    printf("%s", s);
}


2022-09-22 22:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.