2.5 C/C++汇总

## sizeof(数组名) 与 数组长度

int a[] = {1, 2, 3, 4};

cout << sizeof(a);  //16

char b[] = "abc";

cout << sizeof(b);  //4

cout <<strlen(b);  //3

char c[] = {'1', '2', '3'};

cout << sizeof(c);  //3

cout << strlen(c);  //3

当数组作为函数参数传递当时候, 表示的是指针, 用sizeof求出来的是计算机字长。

long long a=0;
char c='c';
char * pc = &c;
cout << sizeof(a) << endl;  //8
cout << sizeof(long long) << endl;  //8
cout << sizeof(c) << endl;  //1
cout << sizeof(char) << endl;  //1
cout << sizeof(pc) << endl;  //4

参考https://blog.csdn.net/ddl2111/article/details/80372563

## 浮点数比较

不要用 a == b的办法判断两个浮点数是否相等,包括不要用  a== 0的办法判断浮点数 a是否等于0。因为浮点数是有误差的。

应该用  a-b > -eps && a-b < eps  ,即a和b的差的绝对值小于某个很小值 eps的办法来判断a和b是否相等。

如果结果要保留小数点后面n位,那么 eps可以取 10的-(n+1)次方。

参考https://www.cnblogs.com/huashanqingzhu/p/7221791.html

## atoi和stoi

vs环境下:
stoi函数默认要求输入的参数字符串是符合int范围的[-2147483648, 2147483647],否则会runtime error。
atoi函数则不做范围检查,若超过int范围,则显示-2147483648(溢出下界)或者2147483647(溢出上界)。
stoi头文件:<string>,c++函数
atoi头文件:<cstdlib>,c函数

参考https://blog.csdn.net/acm_1361677193/article/details/52740542

## C语言中结构体定义

struct test
{
    int a;
};
/*
    定义一个结构体,名字是test,这样就可以使用struct test 来定义变量。比如
    struct test a;
*/
typedef struct test T;
/*
    定义一个自定义类型T,其代表含义为struct test.
    T a;和之前的struct test a;一个效果。
*/
//两个可以合并。
typedef struct test
{
    int a;
}T;

参考https://zhidao.baidu.com/question/434946748265683404.html

## malloc函数与free函数

- malloc函数

全称是memory allocation,中文叫动态内存分配,用于申请一块连续的指定大小的内存块区域以void*类型返回分配的内存区域地址,当无法知道内存具体位置的时候,想要绑定真正的内存空间,就需要用到动态的分配内存。void* 类型表示未确定类型的指针。C,C++规定,void* 类型可以通过强制类型转换为任何其它类型的指针。

void *malloc(size);

参数:size //字节数

返回值:成功返回分配空间的首地址,失败返回 NULL

例如:

int * p;

p = (int *) malloc(sizeof(int));

- free函数 

与malloc函数配对使用,释放malloc函数申请的动态内存。

void free(void *ptr);

参数:ptr //空间的首地址

返回值:无

 

## c/c++ int long float double 表示范围

参考https://blog.csdn.net/xuexiacm/article/details/8122267

 

## cin和gets()的区别

参考https://blog.csdn.net/danny_2016/article/details/78873402

## strcpy()函数和strcpy_s()函数的使用及注意事项

参考https://blog.csdn.net/leowinbow/article/details/82380252

## 如何定义一个长度超过一百万的数组

参考https://zhidao.baidu.com/question/1381792074340915140.html

## 求最大公约数的三种方法

参考https://blog.csdn.net/qq_31828515/article/details/51812154

## C语言通过socket编程实现TCP通信

  参考https://blog.csdn.net/jinmie0193/article/details/78951055

  https://blog.csdn.net/guo8113/article/details/26448011

## windows下gcc/g++的安装与配置

  参考https://www.cnblogs.com/MessiXiaoMo3334/p/11478290.html

原文地址:https://www.cnblogs.com/dhfly/p/14713583.html