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

查看:77
本文介绍了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天全站免登陆