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

Asked 1 years ago, Updated 1 years ago, 143 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.