快速ptr和ref的问题 [英] quick ptr's and ref's question

查看:65
本文介绍了快速ptr和ref的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有人可以向我解释为什么下面的代码中为char数组而不是int数组引发异常吗?

感谢您提供任何信息.

Hi,

Can someone please explain to me why an exception is thrown in the below code for the char array but not for the int array?

Thanks for any information.

void swap(int &i, int& j)
{
    int t = i;
    i = j;             // NO PROBLEM HERE
    j = t;
}
void swap(char &i, char &j)
{
    char  t = i;
    i = j;              // EXCEPTION THROWN !  ACCESS VIOLATION !
    j = t;
}


int main()
{

    char * temp = "abc";
    int ints[3] = {1, 2 ,3 };
    std::cout << ints[0] << " " << ints[1] << endl;
    swap(ints[0], ints[1]);
    std::cout << ints[0] << " " << ints[1] << endl;;

    std::cout << temp[0] << " " << temp[1] << endl;
    swap(temp[0], temp[1]);
    std::cout << temp[0] << " " << temp[1] << endl;
    return 0;
}

推荐答案

问题出在char* temp = "abc"和C ++的不完善类型系统中.
The problem is in the char* temp = "abc" and in the imperfect type system of C++.
int ints[3] = {1, 2, 3}; 


实际上是3个整数的数组,其初始值为1,2,3. int []不是const,可以更改值(就像在swap中分配i=j; j=t;时所做的那样.


is actually an array of 3 integers, whose initial values are 1,2,3. The int[] is not const and the value can be changed (as you do when assigning i=j; j=t; in your swap.

char* temp="abc",


实际上是指向char的指针,该char初始化为指向字符串常量"abc"的第一个字符,该字符被视为常量.
(是的:其类型应为const char*,但也可以转换为char*以保持C的向后兼容性).
您的i=j试图写入只读内存页面.

试试


is actually a pointer to a char, that is initializad to point to the first character of the string literal "abc" that is treated as a constant.
(yes: its type should be const char* but is also convertible to char* to retain C backward compatibility).
Your i=j is trying to write into a read-only memory page.

Try

char temp[4] = {''a'', ''b'', ''c'', ''\0'' };


应该与int一样工作.


Should work as with the int do.


因为"abc"是一个常量字符串...

这使得temp成为指向只读字符串的指针.

由于尝试写入只读内存而导致访问冲突!

尝试使用:
Because "abc" is a constant string...

Which makes temp a pointer to a read-only string.

You get an access violation because you are trying to write to read-only memory!

Try it with:
char temp[] = { 'a', 'b', 'c', '\0'};

,它将再次运行.


这篇关于快速ptr和ref的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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