C++常见错误
shantf93
这个作者很懒,什么都没留下…
展开
-
C++函数参数中指针传递的问题
第一类问题:z指针作为函数参数的传递问题在将一个指针传入函数并在函数中为其分配内存空间的时候会出现下面的常用错误:#include <cstring>using namespace std; //void GetMemory( char *p )//假如这里是*p那么在函数中就不是p指针本身而是临时变量,所以最后分配的空间并不是为原来的p分配的 void GetMemo...原创 2018-03-31 10:03:31 · 380 阅读 · 0 评论 -
malloc函数使用时注意的点
1.一定要注意使用malloc函数分配内存后一定要判断内存分配是否成功一旦不成功就需要做相关处理2.一定要在内存使用结束后将malloc分配的内存free释放掉。3.一定要将释放内存后的指针指向nullptr;void GetMemory( char **p, int num ){ *p = (char *) malloc( num );}void Test( void ){ char *str ...原创 2018-03-31 10:26:54 · 3262 阅读 · 1 评论 -
BOOL,int,float,指针变量 与“零值”比较的 if 语句
分别给出BOOL,int,float,指针变量 与“零值”比较的 if 语句(假设变量名为var)BOOL: if(!val)int: if(val==0)float: const float EP=0.00001;if((val-0.0)>-EP&&(val-0.0)<-EP)指针: if(val==nullptr)考查对0值判断的“内功”,BOOL型变量的0判断完全...原创 2018-03-31 10:33:41 · 375 阅读 · 0 评论 -
宏的一些副作用
转载自: https://blog.csdn.net/pingnning/article/details/47371291、优先级问题 1) 传入变量优先级 #define MULTI(a,b) a * b MULTI(1+2,3) => 1 + 2 * 3 其实是想要(1 + 2) * 3 2) 作为值返回时,类似1) #define ADD(a,b) (...转载 2018-03-31 11:28:23 · 1249 阅读 · 0 评论 -
C++函数标准头
#ifndef __INCvxWorksh#define __INCvxWorksh#ifdef __cplusplusextern "C" {#endif/*...*/#ifdef __cplusplus}#endif#endif /* __INCvxWorksh */#ifndef __INCvxWorksh#define __INCvxWorksh编译宏的作用是为了防止重...原创 2018-03-31 11:44:11 · 1409 阅读 · 0 评论 -
字符串左移右移
在剑指offer里有左移的题目,牛客网上也有右移的题目。简单的总结一下。方法一:假如使用string的话比较方便。string LeftRotateString(string str, int n) { if(n<=0||str.size()==0) return str; int len=str.size(); n=n%len; str+=s...原创 2018-03-31 13:41:00 · 5757 阅读 · 3 评论 -
编写 string成员函数
class string{public: string(const char* str= nullptr); string(const string& other); ~string(void); string&operator=(const string& other);private: char* m_data;};...原创 2018-03-31 14:16:12 · 294 阅读 · 0 评论 -
加法考虑溢出的问题
写一个函数返回1+2+3+…+n的值(假定结果不会超过长整型变量的范围)既然这里提示不超过长整形那么就要考虑结果是否是int。int Sum( int n ){ return ( (long)1 + n) * n / 2; //或return (1l + n) * n / 2;}这里将1进行转换,转换为长整形。所以后面都会转换为long。...原创 2018-03-31 14:28:30 · 1732 阅读 · 0 评论