为什么我得到的;初始化“的char *'类型'为const char *'的前pression丢弃预选赛? [英] Why I get; initializing 'char *' with an expression of type 'const char *' discards qualifiers?

查看:552
本文介绍了为什么我得到的;初始化“的char *'类型'为const char *'的前pression丢弃预选赛?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白,为什么我自己获得这样的警告:

I can't figure out why I get this warning from clang by myself:

function_prototype_const_modifier.c:13:8: warning: initializing 'char *' with an
      expression of type 'const char *' discards qualifiers
      [-Wincompatible-pointer-types]
        char *ptr1 = source;
              ^      ~~~~~~
1 warning generated.

在code是非常简单的。

The code is very simple

#include<stdio.h>

char *my_strcpy(char *destination, const char *source);

int main(void) {
    char str1[] = "this is something";  
    char str2[] = "123456789123456789";
    my_strcpy(str2, str1);
    puts(str2);
    return 0;
}
char *my_strcpy(char *destination, const char *source) {
    char *ptr1 = source;
    char *ptr2 = destination;
    while(*ptr1 != '\0') {
        *ptr2++ = *ptr1++;
    }
    *ptr2 = '\0';
    return destination;
}

任何想法?

推荐答案

为const char * ,一个指向字符常量的,所以人物不能被取消引用指针被改变。(即源[0] ='A'; 是违反约束)

source is a const char *, a pointer to const characters, so the characters cannot be changed by dereferencing the pointer (i. e. source[0] = 'A'; is a constraint violation).

然而,将其分配给的char * 丢弃的这种约束;一个简单的的char * 提示字符由 ptr1的指针指向不是恒定的,现在您可以自由写 ptr1的[0] ='A'; 没有得到编译器错误(一个诊断消息)

However, assigning it to a char * discards this constraint; a simple char * suggests that the characters pointed to by the ptr1 pointer are not constant and you can now freely write ptr1[0] = 'A'; without getting compiler errors (a "diagnostic message").

考虑一下这意味着当你在一个字符串传递。由于一个字符串文字是只读(这是一个为const char [] ),试图修改其内容是不确定的行为。所以,如果你

Consider what this means when you pass in a string literal. Since a string literal is "readonly" (it's a const char []), trying to modify its contents is undefined behavior. So if you call

my_strcpy(destination, "Constant String");

但在code由于某种原因,你写

but in the code for some reason you write

ptr1[0] = 'A';

您不会得到一个编译器的诊断信息,因为 ptr1的是一个指向非const字符,但你的程序仍然会调用未定义行为(在实践中,大多数可能崩溃,因为字符串放在只读存储器地区)。

you won't get a compiler diagnostic message because ptr1 is a pointer to non-const chars, but your program will still invoke undefined behavior (and in practice, most likely crash, since string literals are placed in readonly memory regions).

这篇关于为什么我得到的;初始化“的char *'类型'为const char *'的前pression丢弃预选赛?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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