發表文章

C語言練習題:指標(C language exercise: Pointer)

指標的慣念可以看  C語言: 超好懂的指標,初學者請進 Pointer concepts: 1.  Pointers in C Programming: What is Pointer, Types & Examples 2.  Introduction to C Pointers 🧩 學習脈絡 基礎操作 :從宣告、取值開始(練習一~三)。 進階應用 :陣列、指標運算、字串處理(練習四~八)。 安全與抽象 :空指標檢查、函式指標(練習九~十)。 ⚠️ 注意事項 記憶體管理 : malloc() 與 free() 必須成對使用,避免記憶體洩漏。 空指標檢查 :存取 NULL 指標會造成程式崩潰。 函式指標 :靈活但容易出錯,需確保型別一致。 練習一:基本語法 宣告指標、取變數位址、透過指標取值。 範例程式展示 & 與 * 的基本用法。 設計一個C語言程式來呈現指標的語法,例如宣告、取址、取值等。 Exercise 1: Basic Syntax Design a C program to demonstrate the basic syntax of pointer. Such as declaration, address and value.  練習一參考解法: Exercise 1 solution: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 /* Pointer Basic Syntax Author: Holan */ #include <stdio.h> #include <stdlib.h> int main () { int n = 50 ; // declaration int * ip; // assignment ip = & n; printf( "The value of &n:%X \n " , & n); printf( "The value of n:%i \n " , n); printf( "T...

程式競程入門:基本輸入與輸出

此篇文章是以 C/C++ 程式語言做為程式競程中,資料的輸入與輸出來示範的。 在程式競賽(APCS、ZeroJudge、UVa Online Judge)中,最重要的第一步就是學會如何讀取輸入資料(Input)以及輸出答案(Output)。 一、C++語言的輸入與輸出 C++ 主要使用 iostream 標頭檔中的 cin 與 cout。在競程中,為了提升 standard I/O 的效能,通常會在 main() 函式開頭加上「I/O 優化」程式碼。 輸出(Output) C++使用 cout  與運算子 << 將資料顯示在螢幕上。 基本語法 cout << "要輸出的文字內容" ; cout << variableName; 範例 # include <iostream> using namespace std; int main () { int x = 33 ; cout << "變數x的數值為:" << x; return 0 ; } 執行結果: 變數x的數值為:33 輸出多個資料 string name = "Tom" ; int age = 18 ; cout << "姓名:" << name << " 年齡:" << age; 輸出結果: 姓名:Tom 年齡:18 換行 cout << "第一行" << endl; cout << "第二行" << endl; 或 cout << "第一行\n" ; cout << "第二行\n" ; 輸入(Input) C++使用 cin  與運算子 >> 從標準輸入讀取資料。 基本語法 cin >> variableName; 範例 # include <iostream> using namespace std;...