Just trying to understand how to address a single character in an array of strings. Also, this of course will allow me to understand pointers to pointers subscripting in general.
If I have char **a
and I want to reach the 3rd character of the 2nd string, does this work: **((a+1)+2)
? Seems like it should...
Also, each character in a string can be accessed using an index similar to indexing in the array. In the string's case, when we read in the form of a character array using scanf(), it will stop the string or reading function when it finds the first white space. To avoid this gets() function can be used.
String Indexing Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.
Use the array subscript operator [] . It allows you to access the nth element of a pointer type in the form of p[n] . You can also increment the pointer by using the increment operator ++ .
If you need to take an character array as input you should use scanf("%s",name), printf("%s",name); rather than using the %c . The %c returns the pointer to a character which cannn't be stored in pointer to character array.
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).
Alternatively, this expression:
a[1][2]
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With