数组和指针的区别 [英] Difference between array and pointer

查看:115
本文介绍了数组和指针的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我用自制的strcpy的功能有点麻烦。现在它虽然,但我有点糊涂了!

 的char * A =你好,世界! //作品
焦B〔=]你好,世界! //也适用的strcpy(一,你好!); //分段故障
的strcpy(二,哈哈!!); //作品..

在哪里是区别?为什么字符指针导致段错误?

为什么这甚至工作?

 的char * A =哈哈; //作品
A =LOL //作品..


解决方案

 的char * A =你好,世界!

为您提供了一个指向一个字符串。字符串文字可以在只读存储器存在,因此其内容不能改变。

 的char * A =哈哈; //作品
A =LOL //作品..

改变指针 A 来指向不同的字符串。它不试图修改任何字符串的内容,所以是安全的/正确的。

 字符B〔=]你好,世界!

声明在堆栈上的数组和一个字符串的内容初始化它。栈内存是可写的所以它的万无一失改变这种存储器的内容。

Yesterday I had a little trouble with a homemade "strcpy" function. It works now though but I'm a little confused!

char* a = "Hello, World!"; //Works
char b[] = "Hello, World!"; //Works also

strcpy(a, "Hello!"); //Segmentation fault
strcpy(b, "Haha!!"); //Works..

Where is the difference? Why does the char pointer cause a "Segmentation fault"?

Why does this even work? :

char* a = "Haha"; //works
a = "LOL"; //works..

解决方案

char* a = "Hello, World!";

gives you a pointer to a string literal. A string literal may exist in read only memory so its contents cannot be changed.

char* a = "Haha"; //works
a = "LOL"; //works..

changes the pointer a to point to a different string literal. It doesn't attempt to modify the contents of either string literal so is safe/correct.

char b[] = "Hello, World!"

declares an array on the stack and initialises it with the contents of a string literal. Stack memory is writeable so its perfectly safe to change the contents of this memory.

这篇关于数组和指针的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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