owned this note
owned this note
Published
Linked with GitHub
# 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

```clike
int *ptr = 0x1000;
printf("%x",*ptr + 1);
printf("%x",*(ptr + 1));
```
Assume little endian is used.
:::spoiler Answer
Output:
0x67452302
0xEFCDAB89
:::