字符*和strcpy的的char []之间的差值() [英] difference between char* and char[] with strcpy()

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

问题描述

我一直有麻烦的我,虽然我理解的问题,在过去的几个小时。这里是我的麻烦:

I've been having trouble the past couple hours on a problem I though I understood. Here's my trouble:

void cut_str(char* entry, int offset) {
    strcpy(entry, entry + offset);
}

char  works[128] = "example1\0";
char* doesnt = "example2\0";

printf("output:\n");

cut_str(works, 2);
printf("%s\n", works);

cut_str(doesnt, 2);
printf("%s\n", doesnt);

// output:
// ample1
// Segmentation: fault

我觉得有一些事情的char * /的char [],我不是到这儿。

I feel like there's something important about char*/char[] that I'm not getting here.

推荐答案

的区别在于犯规点属于一个字符串常量的内存,因此是不可写的。

The difference is in that doesnt points to memory that belongs to a string constant, and is therefore not writable.

当你做到这一点。

char  works[128] = "example1\0";

,编译器的拷贝的一个不可写的字符串的内容到一个可写的阵列。 \\ 0 不是必需的,顺便说一句。

the compiler copies the content of a non-writable string into a writable array. \0 is not required, by the way.

当你做到这一点,但是,

When you do this, however,

char* doesnt = "example2\0";

编译离开指针指向一个不可写的存储器区域。同样, \\ 0 将被编译器插入。

如果您使用的是 GCC ,你可以把它提醒你有关初始化写的char * 与字符串。该选项 -Wwrite串。你会得到像这样的警告:

If you are using gcc, you can have it warn you about initializing writable char * with string literals. The option is -Wwrite-strings. You will get a warning that looks like this:

 warning: initialization discards qualifiers from pointer target type

来声明犯规指针的正确方法如下:

const char* doesnt = "example2\0";

这篇关于字符*和strcpy的的char []之间的差值()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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