C語言中,關於陣列和結構體變數的的預設初值問題
阿新 • • 發佈:2019-01-23
結果自己跑一下,需要自己修改不同賦初值情況來驗證,乾貨就是註釋
#include <iostream> #include <stdio.h> using namespace std; int val;//外部變數預設值為0 typedef struct node{int a, b;}node; //結構體預設值同陣列,這裡的結構體node只是聲明瞭結構體的結構,node可以在外部宣告全域性結構體例項n0,也可以在函式內部宣告區域性結構體例項n1 node n0; int main() { cout << val << endl; char ch[2][2];//char型陣列同int型陣列初值說明 for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) printf("%c ",ch[i][j]); cout << endl; int a[2][2] = {10, 20};// 對於陣列初始化,只能省略最右邊連續元素初值語法規定(前面有賦值,最右邊未賦值的元素預設為賦0值) //區域性作用域陣列不賦初值,元素預設初值隨機;對於靜態陣列和外部陣列,預設初值為0; for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) cout << a[i][j] << " "; struct test{int a; double b;}; struct test t;//結構體預設值同陣列;t = {}時,內部預設初值為0 //cout << endl << t.a << " " << t.b; printf("%d, %f\n", t.a, t.b); cout << endl << n0.a << " " << n0.b; node n1 = {}; cout << endl << n1.a << " " << n1.b; return 0; }