[C/C++]C语言-踩坑记录

很久没写C语言的代码,发现很多小细节,记下来备查。

0. C语言常规头文件

#include <stdlib.h>
#include <stdio.h>

1. 二维数组的开辟和释放-malloc()&free()

double ** a;   //a[m][n]
a = (double **) malloc (sizeof(double *) *m);
    for (int i = 0; i < m; i ++)
        a[i] = (double *) malloc (sizeof(double) *n);
for (int i = 0; i < m; i ++){
    free(a[i]);
}
free(a);

2. 结构体指针

参考这篇文章:https://blog.csdn.net/qq_41936805/article/details/87542219
在读的时候用->还是.要特别注意。

struct{
	int x, y;
}point;

point *p = {1, 2};
int xx;
xx = p->x;
xx = (*p).x;

3. C语言生成随机数

一般情况:

a = rand();

限定范围:

设范围区间为(max,min),那么只需rand%(max-min+1)+min 即可

a = rand()% 50 + 1;
//生成(1,50)的随机整数

生成连续随机数

srand((unsigned)time(0);
a = rand();

在短时间内连续生成随机数

如果程序的运行时间很短,在毫秒内,此时time(0)不能作为有区分度的“种子”。此时要再加入一层随机:

srand((unsigned)time(0) + (unsigned)rand());
a = rand();

参考这篇笔记:https://www.cnblogs.com/dosu/p/12468150.html

4. 使用Dev-C++编译C语言的一些奇怪报错

[Error]: request for member ‘xxx’ in something not a structure or union.

由于结构体指针引用错误,如果它是指针,就在它后边用->,如果它不是指针,就在它后边就用.
与以上2. 结构体指针类似,不过这个问题主要发生在调用函数传入结构体指针参数(&point)时。
还可以参考这篇笔记:https://www.cnblogs.com/annie-fun/p/6369872.html

[Error] 'for' loop initial declarations are only allowed in C99 or C11 mode

在for循环里声明变量只允许在C99或C11模式, 需要在工具(Tools)/编译选项(complier option)/代码生成下的语言标准选择C99
image

参考这篇笔记:https://blog.csdn.net/qq_38316655/article/details/82830565

posted @ 2021-12-28 22:52  CAMILIA  阅读(68)  评论(0)    收藏  举报