C 語言不支援 arr1 = arr2; 或 arr = {1,2,3}; (僅初始化時可用大括號)。賦值必須逐元素或呼叫庫函數。
int m[2][2];
float f[3];
/* 逐元素 */
m[0][0] = 0; m[0][1] = 17; m[1][0] = 21;
f[0] = 109.5f; f[1] = -8.29f; f[2] = 0.7f;
/* 迴圈賦值 (較實用) */
for (int i = 0; i < 3; ++i) f[i] = i * 1.5f;
/* 結構體陣列可整體賦值 (C99 指定初始化器僅限初始化) */
struct Pt { int x, y; } pts[2];
pts[0] = (struct Pt){1,2}; /* 複合常值 (C99) */
pts[1] = pts[0]; /* 結構體賦值合法 */
char s[30];
strcpy(s, "Good News!"); /* 簡單、不檢查長度,危險 */
strncpy(s, "Good News!", sizeof s); /* 複製至多 n 字元,不保證以 \0 結尾 */
s[sizeof s - 1] = '\0'; /* 強制終止 */
/* 推薦:snprintf 保證不溢位、保證以 \0 結尾、回傳所需長度 */
snprintf(s, sizeof s, "Good News!");
char buf[200];
snprintf(buf, sizeof buf,
"The writer would like to thank you for"
"your interest in his book. He hopes you"
"can get some helps from the book.");
/* 編譯器自動串接相鄰字串常值 */
char *f[2];
int *a[2];
f[0] = "thank you"; /* 指向字串常值 (唯讀) */
f[1] = "Good Morning";
/* 整數指標陣列:需先配置指向物件 */
int v1 = 1, v2 = -11;
a[0] = &v1;
a[1] = &v2;
/* 或動態配置 */
a[0] = malloc(sizeof(int));
*a[0] = 1;
a[1] = malloc(sizeof(int));
*a[1] = -11;
| 宣告 | 儲存內容 | 賦值方式 | 可修改內容 |
|---|---|---|---|
char s[30]; | 字元陣列 (緩衝區) | strcpy(s, ...) | 是 |
char *p; | 指標 (存位址) | p = "literal"; 或 p = malloc(...) | 視指向物件而定 |
char *f[2]; | 指標陣列 | f[0] = "..."; | 視各指標指向而定 |
char s[10]; s = "Hi"; → strcpy(s, "Hi");char *p; strcpy(p, "Hi"); (野指標) → char *p = malloc(20); strcpy(p, "Hi");strncpy(s, "Long", sizeof s); 忘加 s[sizeof s-1]='\0'; → 改用 snprintf。char *p = "Hi"; p[0] = 'B'; (修改常值 UB) → char p[] = "Hi"; p[0] = 'B';snprintf:安全、可攜、可檢查截斷。#define MAX_PATH 260,避免魔術數字。struct Item { char *name; int val; } items[2]; 語意更清晰。std::vector 免去手動管理。