char s[] 和 char *s 有什么区别? [英] What is the difference between char s[] and char *s?

查看:33
本文介绍了char s[] 和 char *s 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,可以在如下声明中使用字符串文字:

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

char s[] = "hello";

或者像这样:

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.

推荐答案

这里的区别在于

char *s = "Hello world";

会将 "Hello world" 放在内存的只读部分,并使 s 成为一个指针,使任何写入对该内存的操作非法.

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.

在做的时候:

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

合法.

这篇关于char s[] 和 char *s 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆