且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从c中的字符串数组访问单个字符?

更新时间:2023-11-08 16:31:04

差不多,但不太完全.正确的答案是:

Almost, but not quite. The correct answer is:

*((*(a+1))+2)

因为您需要先取消对实际字符串指针之一的引用,然后再取消对所选字符串指针的引用,直到所需的字符. (请注意,我在其中添加了额外的括号以简化操作顺序.)

because you need to first de-reference to one of the actual string pointers and then you to de-reference that selected string pointer down to the desired character. (Note that I added extra parenthesis for clarity in the order of operations there).

或者,此表达式:

a[1][2]

也将起作用!...也许是首选,因为您尝试执行的操作的意图更加明显,并且符号本身更加简洁.对于刚接触该语言的人员来说,这种形式可能不会立即显而易见,但是可以理解,数组表示法起作用的原因是因为在C语言中,数组索引操作实际上只是等效指针操作的简写形式.即:*(a + x)与a [x]相同.因此,通过将该逻辑扩展到原始问题,可以将两个单独的指针解引用操作层叠在一起,从而表达式a [x] [y]等效于*((*(a + x))+ y).

will also work!....and perhaps would be preferred because the intent of what you are trying to do is more self evident and the notation itself is more succinct. This form may not be immediately obvious to people new to the language, but understand that the reason the array notation works is because in C, an array indexing operation is really just shorthand for the equivalent pointer operation. ie: *(a+x) is same as a[x]. So, by extending that logic to the original question, there are two separate pointer de-referencing operations cascaded together whereby the expression a[x][y] is equivalent to the general form of *((*(a+x))+y).