C语言学习笔记(四)

1. char *name = malloc(20);

  name = “abcdef”;

这两条语句合起来会导致内存泄露,因为name先指向堆(heap),后又指向了常量区。

2.共用体所有的成员共用一段内存:

  union data{

    short int i;

    char ch;

  }share;

  int a = share.ch;表示用(char)的格式解释共用体所占的空间。a.任何时刻只有一个变量。b.不能在定义的时候赋值。c.同类型的共用体变量是可以整体赋值的。d.共用体变量起作用的是最后一次存放的成员。

example:

  

[root@localhost test]# gcc 12_13_2.c

[root@localhost test]# ./a.out

65

[root@localhost test]# cat 12_13_2.c

#include <stdio.h>

union data

{

short int i;

char ch;

}share;

int main()

{

int a;

share.i = 65+256;

a = share.ch; //表示用(char)的格式解释共用体所占的空间

printf(“%d\n”,a); //结果是65

}

3.malloc()分配后不初始化数据,calloc()分配后数据初始化为零。realloc()分配后所返回的指针不一定是原来的那个指针。

4.结构体的对齐特性:

  结构体内的元素具有对齐特性(一般是4字节对齐),结构体本身也有对齐特性(与其所占内存最大的那个元素的大小对齐)。而且整个结构体的长度必须是齐对齐特性的倍数。

  两个同类型的结构体可以整体赋值,如

  struct AnyOne a, b;

  a = b;    //这是可以的

5.NULL在C和C++中的定义:

  

  #undef NULL

  #if defined(__cplusplus)

    #define NULL 0

  #else

    #define NULL ((void *)0)

  #endif

6.查看堆(heap)的分配和释放:

  [root@localhost test]# valgrind –tool=memcheck –leak-check=full ./a.out

7.umask的作用:将对应的位取反,若umask=022,则将组和其他用户的w权限清零。

8.判断一个变量是不是无符号数:

  #define IS_UNSIGNED(a) ((a >= 0) ? (~a > 0 ? 1 : 0) : 0)

9.

[root@localhost test]# cat 12_13_4.c

#include <stdio.h>

#include <string.h>

void func(char str[50])

{

printf(“%d, %d\n”, sizeof(str), strlen(str));

}

int main()

{

char s[50] = “abcdefght”;

func(s);

}

[root@localhost test]# gcc 12_13_4.c

[root@localhost test]# ./a.out

4, 9

[root@localhost test]#

void func(char str[50])这里的50没有任何意义。sizeof(str)这里str代表数组首元素的地址。

10.

[root@localhost test]# cat 12_13_5.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main()

{

char stra[] = “HelloWorld”;

char *strb = stra;

printf(“%d, %d\n”, sizeof(stra), sizeof(strb++)); //stra代表整个数组,11是因为要算上’\0′

printf(“%d, %d\n”, strlen(strb), strlen(strb++)); //参数从右到左计算

   //sizeof()是个关键字,在预编译时已经计算出了大小,不做运算

}

[root@localhost test]# gcc 12_13_5.c

[root@localhost test]# ./a.out

11, 4

9, 10

[root@localhost test]#

11.

  函数指针:

例如,

int func(int x); /* 声明一个函数 */

int (*f) (int x); /* 声明一个函数指针 */

f=func; /* 将func函数的首地址赋给指针f */

赋值时函数func不带括号,也不带参数,由于func代表函数的首地址,因此经过赋值以后,指针f就指向函数func(x)的代码的首地址。

  指针函数:

类型标识符 *函数名(参数表)

例如,

int *f(x,y);

12.kill -l :列出所有信号

13.注意将while(1)和sleep()(睡眠)区别开来。

14.不可重入函数:

  a.函数返回值是指针,,传递给函数的参数有指针。

  b.内部有malloc()或free()调用的函数。

  c.使用了全局数据结构的函数。

  d.实现时用了标准I/O函数。

可重入函数以xxxxx_r()表示,(后面带了”_r”)。

15.alarm定时产生的误差是比较大的。settimer可以用来精确定时。

自信的生命最美丽!

C语言学习笔记(四)

相关文章:

你感兴趣的文章:

标签云: