Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an individual character from an array of strings in c?

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...

like image 952
sdellysse Avatar asked Mar 03 '09 15:03

sdellysse


People also ask

How do you access a character in an array of strings?

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.

How do you access individual characters in a string?

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.

How do you access elements in a character array?

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 ++ .

How do you read a character array?

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.


1 Answers

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).

like image 156
Tall Jeff Avatar answered Nov 02 '22 13:11

Tall Jeff