Sunday, July 15, 2018

c - What is the difference between char s[] and char *s?



In C, one can use a string literal in a declaration like this:



char s[] = "hello";


or like this:




char *s = "hello";


So what is the difference? I want to know what actually happens in terms of storage duration, both at compile and run time.


Answer



The difference here is that



char *s = "Hello world";



will place "Hello world" in the read-only parts of the memory, and making s a pointer to that makes any writing operation on this memory illegal.



While doing:



char s[] = "Hello world";


puts the literal string in read-only memory and copies the string to newly allocated memory on the stack. Thus making



s[0] = 'J';



legal.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...