JJJJJJ
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Pointer ## 1 What is the output of the following program? ```c # include<stdio.h> # include<stdlib.h> void fun(int *a) { a = (int*)malloc(sizeof(int)); } int main() { int *p; fun(p); *p = 6; printf("%d\n",*p); getchar(); return(0); } ``` :::spoiler Answer `[1] 14793 bus error ./test.out`, since `int* p` is pointing to a random memory location。 因為在 C 中 function 是 pass by value,所以正確的做法是使用 pointer to a pointer,如下: ```c # include<stdio.h> # include<stdlib.h> void fun(int **a) { *a = (int*)malloc(sizeof(int)); } int main() { int *p; fun(&p); *p = 6; printf("%d\n",*p); getchar(); return(0); } ``` - [How can I allocate memory and return it (via a pointer-parameter) to the calling function?](https://stackoverflow.com/questions/1398307/how-can-i-allocate-memory-and-return-it-via-a-pointer-parameter-to-the-calling) ::: ## 2 What is the output of the following program? ```c int main() { char a[2][3][3] = {'g','e','e','k','s','f','o', 'r','g','e','e','k','s'}; printf("%s ", **a); getchar(); return 0; } ``` :::spoiler Answer Output: geeksforgeeks Explanation: We have created a 3D array that should have 2*3*3 (= 18) elements, but we are initializing only 13 of them. In C when we initialize less no of elements in an array all uninitialized elements become ‘\0’ in case of char and 0 in case of integers. ```markdown Value at an array can be accessed using array[i] = *(array+i) (expansion of [i]). Similarily, (*p)[i] = *(*(p+i)). So, we need to dereference twice to access the value. If you want to access, array[0][0], you have to use *(*(p+0)+0) = **p;, Similarily, array[0][1] can be accessed using *(*(p+0)+1) = *((*p)+1); Note, *p points to first row (stores address of array[0][0]), and *(p+1) points to second row (stores address of array[1][0]). ``` ::: ## 3 What is the output of the following program? ```c int main() { char str[] = "geeksforgeeks"; int i; for(i=0; str[i]; i++) printf("\n%c%c%c%c", str[i], *(str+i), *(i+str), i[str]); getchar(); return 0; } ``` :::spoiler Answer Output: gggg eeee eeee kkkk ssss ffff oooo rrrr gggg eeee eeee kkkk ssss Explanation: Following are different ways of indexing both array and string. ```c arr[i] *(arr + i) *(i + arr) i[arr] ``` So all of them print same character. - [你所不知道的C語言:指標篇](https://hackmd.io/@sysprog/c-#Pointers-vs-Arrays) ::: ## 4 What is the output of the following program? ```c int main() { char arr[] = {1, 2, 3}; char *p = arr; printf(" %d ", sizeof(p)); printf(" %d ", sizeof(arr)); getchar(); } ``` :::spoiler Answer Output: 4(machine dependent) 3 Pointer 的 size 一般來說 16-bit system 會是 2 bytes,32-bit 會是 4 bytes,64-bit 會是 8 bytes,但是並不是一定如此。 - [Is the sizeof(some pointer) always equal to four?](https://stackoverflow.com/questions/399003/is-the-sizeofsome-pointer-always-equal-to-four) - [How do I determine the size of my array in C?](https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c) ::: ## 5 What is the output of the following program? ```c #include <stdio.h> int main(void) { char *str[] = { {"MediaTekOnlineTesting"}, {"WelcomeToHere"}, {"Hello"}, {"EverydayGenius"}, {"HopeEverythingGood"} }; char* m = str[4] + 4; char* n = str[1]; char* p = *(str+2) + 4; printf("1. %s\n", *(str+1)); printf("2. %s\n", (str[3]+8)); printf("3. %c\n", *m); printf("4. %c\n", *(n+3)); printf("5. %c\n", *p + 1); return 0; } ``` :::spoiler Answer Output: WelcomeToHere Genius E c p Explanation: `char* m = str[4] + 4;` 會指向 `"HopeEverythingGood"` 的 `E`。 `char* n = str[1];` 會指向 `"WelcomeToHere"` 的開頭。 `char* p = *(str+2) + 4;` 會指向 `"Hello"` 的 `o`。 ::: ## 6 請解釋以下的 variable declarations。 ```clike 1. int p 2. int *p 3. int **p 4. int p[10] 5. int *p[10] 6. int (*p)[10] 7. int (*p)(int) 8. int (*p[10])(int) ``` :::spoiler Answer ```markdown 1. 一個整型數(An integer) 2. 一個指向整型數的指標(A pointer to an integer) 3. 一個指向指標的的指標,它指向的指標是指向一個整型數(A pointer to a pointer to an integer) 4. 一個有10個整型數的陣列(An array of 10 integers) 5. 一個有10個指標的陣列,該指標是指向一個整型數的(An array of 10 pointers to integers) 6. 一個指向有10個整型數陣列的指標(A pointer to an array of 10 integers) 7. 一個指向函數的指標,該函數有一個整型參數並返回一個整型數(A pointer to a function that takes an integer as an argument and returns an integer) 8. 一個有10個指標的陣列,該指標指向一個函數,該函數有一個整型參數並返回一個整型數( An array of ten pointers to functions that take an integer argument and return an integer) ``` ::: ## 7 What is the output of the following program? ```c #include <stdio.h> int main() { int a[5] ={1,2,3,4,5}; int *p = (int *)(&a+1); printf("%d, %d",*(a+1), (*p)); } ``` :::spoiler Answer Output: 2, 0(undefined behavior, could be anything) Explanation: 首先,`&a+1` 等同於 `(&a) + 1`,因為 `&, +` 的 operator precendence 相同,且 associativity 都是 right-to-left,所以 `a` 會從自己開始由右往左的去尋找 operator。 再來,我們使用 gdb 去觀察: ```c (gdb) p &a $3 = (int (*)[5]) 0x7fffffffeba0 (gdb) p &a + 1 $4 = (int (*)[5]) 0x7fffffffebb4 (gdb) p *(&a + 1) $5 = {0, -1530187264, 1438828341, 1, 0} ``` 可看出增加了 `0x7fffffffebb4 - 0x7fffffffeba0` 總共 `20` bytes,剛好是 `5` 個 `int` 的大小。此時,pointer p 指向不在原本 array 範圍內的 memory address,這會導致 undefined behaviour,無法預期到底指針會指向的記憶體位置裡面會有什麼東西。 和以下範例比較: ```clike #include <stdio.h> int main() { int a[5] ={1,2,3,4,5}; int *p = (int *)(a+1); printf("%d, %d",*(a+1), (*p)); } ``` Output: 2, 2 `a + 1` 和 `&a + 1` 的差別在於: `a + 1` 中的 `a` 會指向 array a 的第一個元素,但是 `&a` 則會是 array a 本身的 address,而 [pointer arithmetic](https://www.geeksforgeeks.org/pointer-arithmetics-in-c-with-examples/) 會使得 `&a + 1` 的 `+ 1` 加上的會是整個 array 的大小。 關於為什麼會是加上整個 array 的大小,詳見:[Linus Torvalds 親自教你 C 語言](https://hackmd.io/@sysprog/c-pointer#Linus-Torvalds-%E8%A6%AA%E8%87%AA%E6%95%99%E4%BD%A0-C-%E8%AA%9E%E8%A8%80) ::: ## 8 請填空 ```c void(*(*papf)[3])(char *); typedef __________; pf(*papf)[3]; ``` :::spoiler Answer ```c void (*pf) (char *) typedef void(*pf)(char *); ``` Explaination: A function pointer can be a return value: ```c char *(*get_strcpy_ptr(void))(char *dst, const char *src); ``` which returns a pointer to a function of the form ```c char *strcpy (char *dst, const char *src); ``` 以 ```c void(*(*papf)[3])(char *); ``` 為例,`(*papf)[3]` 是三個 function pointer,points to a function of the form of ```c void(*pf)(char *) ``` ::: ## 9 ```clike int main() { int arr[2] = { 1, 2 }; // 一個有兩個整數元素的陣列型態,其變數名為 arr int arr2[2]; // 一個有兩個整數元素的陣列型態,其變數名為 arr2,但沒有初始化,內部元素可能為隨機值 int *p_arr[2]; // 一個有兩個整數指標元素的陣列型態,其變數名為 p_arr,也沒有初始化 int(*p_arr2[2])[2] = { &arr, &arr2 }; // 一個有兩個指向 int[2] 元素的陣列型態,其變數名為 p_arr2 int(*a1)[2] = &arr; // 一個指向 int[2] 型態的指標,其變數名為 a1,指向 arr return 0; } ``` ## 10 Assertion failed ? ```clike #include <stdio.h> #include <assert.h> int main() { int i = 0; int *p = &i; assert(&(p[0]) == &i); } ``` :::spoiler Answer No. Explaination: 在對指標進行比較與算術運算時,指向非陣列元素的指標會被視作一個指向「只有一個元素的陣列」的第一個元素的指標 ::: ## 11 What is the output of the following program? ```clike void fun(int *p) { static int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf("%d", *p); getchar(); return 0; } ``` :::spoiler Answer Output: 20 Explaination: `fun(p)` 傳入的是 pointer p 的值,而非 pointer p 的 address,因此無法改變 pointer p 指向的 memory location。 以下是對照組: ```clike #include <stdio.h> void fun(int **p) { static int q = 10; *p = &q; } int main() { int r = 20; int *p = &r; fun(&p); printf("%d", *p); getchar(); return 0; } ``` Output: 10 ::: ## 12 What is the output of the following program? ```clike #include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); getchar(); return 0; } ``` :::spoiler Answer Output: 513 on a little endian machine, and 16908800 on big endian machine Explanation: 根據 pointer arithmetic,因為 x 為 pointer to char,因此 `x[0], x[1]` 相當於 `x + 0, x + 1`,單位是一個 char 的大小,也就是 1 byte。 `512` 的 binary form: 10 0000 0000, in hex: 0x00000200 big endian 代表 MSB 在最低的記憶體位置,0x00000200 在 big endian 中的記憶體位置由低往高依序是:00 00 02 00。 而在 little endian 中 MSB 在最高的記憶體位置,所以在 little endian 中的記憶體位置由低往高依序是:00 02 00 00。 因為 char 大小為一個 byte,所以: `x[0] = 1` 代表修改由最低記憶體位置開始算的第一個 byte 的內容為 1。 在 big endian machine 上記憶體位置由低到高在修改完之後長這樣:01 00 02 00 在 little endian machine 上記憶體位置由低到高在修改完之後長這樣:01 02 00 00 `x[1] = 2` 代表修改由最低記憶體位置開始算的第二個 byte 的內容為 1。 在 big endian machine 上記憶體位置由低到高在修改完之後長這樣:01 02 02 00 在 little endian machine 上記憶體位置由低到高在修改完之後長這樣:01 02 00 00 將記憶體裡的內容分別還原成 hex notation: big endian machine:0x01020200,convert to decimal 會是 16908800 little endian machine:0x00000201,convert to decimal 會是 513 至於該如何判斷 machine 是哪一個 endian 呢? /****************************************************************************** By Codeky.dev This code is to demonstrate the Endianness Explanation: ----------- The endianess is how the cpu arrange bytes in memory in Big endian system, MSB is placed at lower address, while in Little endian system, MSB is placed higher address. So, if we have an unsigned integer: 0x00000001 it is represented in the memory as below in both systems | | byte[0] | byte[1] | byte[2] | byte[3] | |----+---------+---------+---------+---------| | BE | 00 | 00 | 00 | 01 | | LE | 01 | 00 | 00 | 00 | If we have a char pointer point to that integer variable, derefenced the pointer will be 00 in BE and 01 in LE That's it :) *******************************************************************************/ ```clike #include <stdio.h> int isLittleEndian() { unsigned int x = 1; return *(char*) &x; } int main() { if (isLittleEndian()) { printf("Little endian\n"); } else { printf("Big endian\n"); } return 0; } ``` ::: ## 13 ```clike #include <stdio.h> int main(void) { char *a[] = {"abc", "def", "ghijk", "lmnop"}; char *b = a[2]; printf("%d\n", sizeof(a)); printf("%d\n", sizeof(b)); printf("%d\n", sizeof(a[2])); printf("%d\n", sizeof(b[2])); return 0; } ``` :::spoiler Answer Output: 32 8 8 1 Explaination: `char *a[]` 可看成 `char ** a`。一個 pointer 在 64-bit machine 上的大小為 8 bytes。 ::: ## 14 ```clike #include <stdio.h> int main() { int a = 3, b = 5; printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]); printf(&a["WHAT%c%c%c %c%c %c !\n"], 1["this"], 2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]); return 0; } ``` :::spoiler Answer Output: Hello! how is this? super That is C ! Explaination: 首先要知道`int printf(const char *restrict format, ...);`。 再來掌握這個觀念: `a[i]` 其實就是 `*(a+i)` 也就是 `*(i+a)`,所以如果寫成 `i[a]` 應該也不難理解了。 同樣邏輯: `printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);` 就等於 `printf(&"Ya!Hello! how is this? %s\n"[a], &"junk/super"[b]);` 也等於 `printf(&("Ya!Hello! how is this? %s\n"[a]), &("junk/super"[b]));` ::: ## 15 ![image](https://hackmd.io/_uploads/H1MTRaxc6.png) ```clike int *ptr = 0x1000; printf("%x",*ptr + 1); printf("%x",*(ptr + 1)); ``` Assume little endian is used. :::spoiler Answer Output: 0x67452302 0xEFCDAB89 :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully