printf和cout有什么区别? [英] What is difference between printf and cout?

查看:395
本文介绍了printf和cout有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++代码中以下两个语句之间有什么区别。?

1. cout<< * p; //错误

2. printf("%d",* p); //没有错误

What is the difference between the following two statements in a c++ code.?
1. cout<<*p; //error
2. printf("%d",*p); //no error

推荐答案

请显示完整的代码。


如果''p''是指向整数,如果它已被正确初始化,则(1)和(2)都会在''p'指向的地址处打印值。


确保你有正确初始化''p'',否则行为未定义。
Please show the complete code.

If ''p'' is a pointer to an integer and if it has been properly initialized then both (1) and (2) print the values at the addresses being pointed to by ''p''.

Make sure that you have properly initialized ''p'', otherwise the behaviour is undefined.


正确代码:

proper code:

展开 | 选择 | Wrap | 行号


printf是一个C函数,没有类型c因此,它不知道你已经尝试了一个没有意义的操作,并且最终尝试了一个超出范围的内存访问,未定义的行为可能导致崩溃。


另一方面来自C ++的手cout是类型感知的,并且检测到你已经尝试打印一个类型结构temp,它不知道如何打印,因此引发编译错误,避免了C代码编译到的越界内存访问。 />


你需要弄清楚你想要做的虚假乐趣(struct temp * p)以及它实际做了什么。
printf is a C function and has no type checking therefore it does not know that you have attempted an operation that makes no sense and that ultimately attempts an out of bounds memory access, undefined behaviour that may cause a crash.

On the other hand cout from C++ is type aware and has detected that you have tried to print a type struct temp that it has no idea how to print and so raises a compile error avoiding the out of bounds memory access that the C code compiles to.


You need to work out that you wanted void fun(struct temp *p) to do and what it actually does.


这篇关于printf和cout有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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