Skip to content

Commit

Permalink
docs: daily 12.8
Browse files Browse the repository at this point in the history
  • Loading branch information
45gfg9 committed Dec 8, 2023
1 parent ed252ce commit c9f7fcf
Showing 1 changed file with 61 additions and 1 deletion.
62 changes: 61 additions & 1 deletion docs/programming/daily/2023.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,67 @@ h5:before {content: unset;}

## December

### 「7」 The differance between `strlen` and `sizeof`.
### 「8」 J lost

Given the following program:

```c linenums="1" hl_lines="7 13"
void xqc(char c[], int i);

int main(void) {
char c[] = "I am a Man of Fortune";
char d[] = "and I must seek my Fortune";

xqc(c + 1, ~1694);
xqc(d - ~3, -65);
printf("%s, %s\n", c, d);
}

void xqc(char c[], int i) {
c = c - 1;
c[0] = ' ';
c[1] = (i & 1) + 'I';
}
```
Which of the following is correct?
A. This program fails to compile, because you cannot assign to an array in line 13.
B. Because of the call-by-value, function `xqc` cannot modify the character arrays in function `main`.
C. Change `1694` in line 7 to `1994`, and the result of the program is the same.
D. This program outputs `I am a Man of Fortune, and J must seek my Fortune`.
<!-- prettier-ignore-start -->
??? note "Answer"
C.
A: Inside function `xqc`, `c` is a pointer type `char *` rather than an array type, because when an array type is used in a function parameter list, it actually is the corresponding pointer type. Therefore, the assignment in line 13 is valid, and it means "to move the pointer `c` one position backward".
B: The function `xqc` can modify the character arrays in function `main`, because it takes the address of the character arrays as parameters. The function `xqc` can modify the contents of the character arrays through the pointers.
C: The `~` operator is the bitwise NOT operator. The `~1694` is equivalent to `-1695`. The `~3` is equivalent to `-4`. Therefore, the calls to function `xqc` are equivalent to:
```c
xqc(c + 1, -1695);
xqc(d - -4, -65);
```
And `i & 1` gets the last bit of `i`. Both `-1695` and `-65` are odd numbers, so `i & 1` is `1`, and the character `1 + 'I'`, which is `'J'`, is assigned. Changing `1694` to `1994` does not change the result of the program, because `~1994` is `-1995`, and `-1995` is also an odd number.
D: This program outputs <code>&nbsp;Jam a Man of Fortune, and J must seek my Fortune</code>.
!!! tip
You don't need to calculate the exact value of `~1694`. All you need to know is that the last bit of `1694` is 0 (since it is an even number), and the bitwise NOT operator will reverse that last bit. Therefore, `~1694` is an odd number, and `i & 1` is `1`. Ditto for `~1994`.
<!-- prettier-ignore-end -->
> 供题人:李英琦
### 「7」 The difference between `strlen` and `sizeof`.
```c linenums="1"
#include <stdio.h>
Expand Down

0 comments on commit c9f7fcf

Please sign in to comment.