什么使这种指针的使用不可预测? [英] What makes this usage of pointers unpredictable?

查看:172
本文介绍了什么使这种指针的使用不可预测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习指针,我的教授提供这段代码作为示例:

I'm currently learning pointers and my professor provided this piece of code as an example:

//We cannot predict the behavior of this program!

#include <iostream>
using namespace std;

int main()
{
    char * s = "My String";
    char s2[] = {'a', 'b', 'c', '\0'};

    cout << s2 << endl;

    return 0;
}

他在评论中写道我们无法预测程序的行为。究竟是什么让它不可预测呢?我看不出有什么错误。

He wrote in the comments that we can't predict the behavior of the program. What exactly makes it unpredictable though? I see nothing wrong with it.

推荐答案

程序的行为是不存在的,因为它是不成形的。 / p>

The behaviour of the program is non-existent, because it is ill-formed.

char* s = "My String";

这是非法的。

正确的行是:

const char* s = "My String";

除此之外,程序很好。你的教授应该喝更少的威士忌!

Other than that, the program is fine. Your professor should drink less whiskey!

这篇关于什么使这种指针的使用不可预测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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