什么是个char []和char * S在C之间的区别? [英] What is the difference between char s[] and char *s in C?

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

问题描述

在C,可以这样做:

char s[] = "hello";

char *s = "hello";

所以,我不知道有什么区别?我想知道在编译时和运行时实际发生的事情进行内存分配。

So I wonder what is the difference? I want to know what actually happens for memory allocation during compile time and run time.

推荐答案

这里的不同之处在于

char *s = "Hello world";

将放在的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.

虽然这样做:

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 []和char * S在C之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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