用C的char []和char *之间的区别 [英] Difference between char[] and char * in C

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

问题描述

什么是用C的char [] S和char * S之间的区别?
据我了解,双方建立做出的指针字符数组。
不过,

What is the difference between char[] s and char * s in C? I understand that both create make 's' a pointer to the array of characters. However,

char s[] = "hello";
s[3] = 'a';
printf("\n%s\n", s);

打印 helao ,而

char * s = "hello";
s[3] = 'a';
printf("\n%s\n", s);

给我一个分段错误。为什么会有这样的区别?
我使用Ubuntu的12.04 GCC。

gives me a segmentation fault. Why is there such a difference? I'm using gcc on Ubuntu 12.04.

推荐答案

在使用个char [] =你好; ,在范围内创建的字符数组目前的功能,因此内存堆栈上进入函数时分配的。

When using char s[] = "hello";, the char array is created in the scope of the current function, hence the memory is allocated on the stack when entering the function.

在使用的char * s =你好; 取值是一个指向一个常量字符串,它的编译器保存在其中被阻止写访问的程序的内存块,因此分段错误。

When using char *s = "hello";, s is a pointer to a constant string which the compiler saves in a block of memory of the program which is blocked for write-access, hence the segmentation fault.

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

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