用的memcpy目标指针为const数据 [英] memcpy with destination pointer to const data

查看:175
本文介绍了用的memcpy目标指针为const数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以为,像 const int的一个声明* A 办法 A INT 指针常量数据,因此不应该能够修改它指向的值。事实上,如果你这样做 const int的一个[] = {1,2,3} ,然后发出 A [0] = 10 你会得到编译器错误。

要我的意料,但是,没有任何预兆下编译和运行就好了。

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;诠释主(){    const int的一个[] = {1,1,1};
    const int的B〔] = {2,2,2};    的memcpy((无效*)及一个[0],(常量无效*)和b [0],3 *的sizeof(int)的);    INT I;
    对于(I = 0; I&下; 3;我++)输出(%d个\\ N,一个由[i]);    返回0;
}

这是为什么允许?这是由于投?当我做的memcpy(安培; A [0],(常量无效*)和b [0],3 * sizeof的(INT)); 编译器立即会产生以下警告:

  cpy.c:在函数'主':
cpy.c:9:3:警告:传递的memcpy丢弃const限定符的参数1指针目标类型[默认启用]
/usr/include/string.h:44:14:注:应为无效* __restrict__',但参数的类型为const int的*'


解决方案

通常施放燮preSS警告。有一个gcc的选项, -Wcast-QUAL 将警告你正在失去管型常量挥发性预选赛。

该程序成功运行,因为用于存储阵列的存储本来就不是只读的,因为他们是在栈上分配。这是一个实现细节和技术上的code可能是失事如果实现真正严格。

声明 A B 作为全局,有一个更大的机会就会死机(仍然不能保证)

I always thought that an statement like const int *a means a is an int pointer to const data and as such one should not be able to modify the value it points to. Indeed if you do const int a [] = {1,2,3} and then issue a[0] = 10 you'll get compiler errors.

To my surprise, however, the following compiles without any warning and runs just fine.

#include <stdio.h>
#include <string.h> 

int main (){

    const int a [] = {1, 1, 1};
    const int b [] = {2, 2, 2};

    memcpy((void*) &a[0], (const void*)&b[0], 3*sizeof(int));

    int i;
    for (i=0; i<3; i++) printf("%d\n",a[i]);

    return 0;
} 

Why is this allowed? Is this due to the cast? When I do memcpy(&a[0], (const void*)&b[0], 3*sizeof(int)); compiler promptly generates the following warning:

cpy.c: In function ‘main’:
cpy.c:9:3: warning: passing argument 1 of ‘memcpy’ discards ‘const’ qualifier from pointer target type [enabled by default]
/usr/include/string.h:44:14: note: expected ‘void * __restrict__’ but argument is of type ‘const int *’

解决方案

Casts usually suppress warnings. There is a gcc option, -Wcast-qual that will warn you about casts that are losing a const or volatile qualifier.

The program ran successfully because the memory used to store the array wasn't actually readonly, because they were allocated on the stack. This is an implementation detail and technically your code could have crashed if the implementation was really strict.

Declare a and b as globals and there's a greater chance it will crash (still not a guarantee)

这篇关于用的memcpy目标指针为const数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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