(原創) 如何对array或struct做初始化? (memset()) (C/C++) (C)

当宣告C/C++的built-in type后,必须马上initialize该变量的值,因为C/C++在宣告变量时,仅为该变量配置了一块内存,却没对该变量设定任何初始值,所以该变量目前的值为宣告该变量前所残留的值,虽可直接使用该变量,但并没有任何意义。

尤其在使用array时,当宣告完array及其大小后,第一件事情就是为array中所有element设定初始值,通常我们会用for来设定

 1#include <string.h>
 2#include <stdio.h>
 3
 4#define ia_size 5
 5
 6int main() {
 7  int ia[ia_size];
 8  for(int i = 0; i != ia_size; ++i) {
 9    *ia = 0;
10  }

11
12  for(int i = 0; i != ia_size; ++i) {
13    printf("%d",*ia);
14  }

15
16  return 0;
17}

用for写最少要两行程序,若使用memset(),只要一行就可搞定
 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : memset0.cpp
 5Compiler    : Visual C++ 8.0 / gcc 4.1.0
 6Description : The memset() function fills the first n
 7              bytes of the memory area pointed to by 
 8              s with constant byte c.
 9Synopsis    : #include <string.h> 
10              void* memset(void* s, int c, size_t n);
11Release     : 11/25/2006
12*/

13#include <string.h>
14#include <stdio.h>
15
16#define ia_size 5
17
18int main() {
19  int ia[ia_size];
20  memset(ia,0,sizeof(ia));
21
22  for(int i = 0; i != ia_size; ++i) {
23    printf("%d",*ia);
24  }

25
26  return 0;
27}

memset()除了可以初始化array外,也可用来初始化struct
 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : memset1.cpp
 5Compiler    : Visual C++ 8.0 / gcc 4.1.0
 6Description : The memset() function fills the first n
 7              bytes of the memory area pointed to by 
 8              s with constant byte c.
 9Synopsis    : #include <string.h> 
10              void* memset(void* s, int c, size_t n);
11Release     : 11/25/2006
12*/

13
14#include <string.h>
15#include <stdio.h>
16
17struct Foo {
18  int no;
19  double d;
20}
;
21
22int main() {
23  Foo foo;
24  memset(&foo,0,sizeof(foo));
25
26  printf("%i\n",foo.no);
27  printf("%d\n",foo.d);
28
29  return 0;
30}

Reference
Linux C函式库详解辞典 P.73, 徐千祥, 旗标出版社

posted on 2006-11-25 15:19  真 OO无双  阅读(22677)  评论(1编辑  收藏  举报

导航