# 2018q3 Homework3 (review) contributed by < danielian1121 > ## 第一題 :::info 第二週 測驗 4 ::: 考慮到以下程式碼: ```clike int B = 2; void func(int *p) { p = &B; } int main() { int A = 1, C = 3; int *ptrA = &A; func(ptrA); printf("%d\n", *ptrA); return 0; } ```  該如何修改,才能讓 `func` 得以變更到 `main` 裡頭 `ptrA` 的內含值? --- 使用指標的指標,避免因為複本的問題而沒有改到 A 的值 ```clike int B = 2; void func(int **p) { *p = &B; } int main() { int A = 1, C = 3; int *ptrA = &A; func(&ptrA); printf("%d\n", *ptrA); return 0; } ``` :::success 延伸問題: 在 GitHub 找出使用 the pointer to the pointer 的 C 語言程式碼,並加以討論 ::: [task monitor for NVIDIA GPUs](https://github.com/Syllo/nvtop) src/nvtop.c 中有一行程式碼 `num_devices = initialize_device_info(&dev_infos, gpu_mask);` 在 src/extract_gpuinfo.c 中第416行發現此 funciton ```clike= unsigned int initialize_device_info(struct device_info **dev_info, size_t gpu_mask) { unsigned int num_devices; nvmlReturn_t retval = nvmlDeviceGetCount(&num_devices); if (retval != NVML_SUCCESS) { fprintf(stderr, "Impossible to get the number of devices : %s\n", nvmlErrorString(retval)); return 0; } *dev_info = malloc(num_devices * sizeof(**dev_info)); struct device_info *devs = *dev_info; unsigned int num_queriable = 0; ... ... ``` 需要對變數做 malloc ,因此使用 pointer to pointer :::info 提問:可以使用 pointer to pointer 來避免複本問題來更改內容,也可以用 return ,以原本題目的範例來說也可以改成這樣 ```clike int B = 2; int func() { return B; } int main() { int A = 1, C = 3; int *ptrA = &A; *ptrA = func(); printf("%d\n", *ptrA); return 0; } ``` 那上述這2種方式各自在哪種場合比較適合呢?還是說其實看個人習慣就好 ::: ## 第二題
×
Sign in
Email
Password
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