用C关于字符指针 [英] About character pointers in C

查看:126
本文介绍了用C关于字符指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这样的定义:

 的char * pmessage =现在是时候了;

在我看来,pmessage将指向一个连续的区域包含在年底这些字符和一个'\\ 0'的内存。所以我从这个,我可以使用指针运算,只要我在这个字符串访问一个个性在这方面的限​​制派生。

那么,为什么他们说,(K&安培; R),修改的个性是不确定的

此外,为什么当我运行下面的code,我得到一个分段故障?

  *(pmessage + 1)='K';


解决方案

在C字符串文字不可修改。字符串文字是在你的程序的源$ C ​​$ C定义的字符串。编译器会频繁地存储在编译的二进制的只读部分字符串,所以真的是你pmessage指针到这个区域,你不能修改。在存在于可修改存储器缓冲器字符串可以使用上述的语法进行修改。

尝试这样的事情。

 为const char * pmessage =现在是时候了;//创建一个新的缓冲区是在栈上和文字复制进去。
字符缓冲区[64];
的strcpy(缓冲区,pmessage);//现在我们可以修改这个缓冲区
缓冲液[1] =K;

如果你只是想,你可以修改字符串,可以尽量避免使用字符串文字用下面的语法。

 字符pmessage [] =现在是时候了;

此方法直接创建字符串作为堆栈上的阵列,并且可以代替被修改。

Consider this definition:

char *pmessage = "now is the time";

As I see it, pmessage will point to a contiguous area in the memory containing these characters and a '\0' at the end. So I derive from this that I can use pointer arithmetic to access an individual character in this string as long as I'm in the limits of this area.

So why they say (K&R) that modifying an individual character is undefined?
Moreover, why when I run the following code, I get a "Segmentation Fault"?

*(pmessage + 1) = 'K';

解决方案

String literals in C are not modifiable. A string literal is a string that is defined in the source code of your program. Compilers will frequently store string literals in a read-only portion of the compiled binary, so really your pmessage pointer is into this region that you cannot modify. Strings in buffers that exist in modifiable memory can be modified using the syntax above.

Try something like this.

const char* pmessage = "now is the time";

// Create a new buffer that is on the stack and copy the literal into it.
char buffer[64];
strcpy(buffer, pmessage);

// We can now modify this buffer
buffer[1] = 'K';

If you just want a string that you can modify, you can avoid using a string literal with the following syntax.

char pmessage[] = "now is the time";

This method directly creates the string as an array on the stack and can be modified in place.

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

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