Reputation: 27
Given I have declared:
char **string;
How do I pass it into another function with a substring starting at a certain position?
I currently have it as:
function((*string)[pos])
intending it to be a substring that begins at position pos
. Any advice?
Upvotes: 0
Views: 227
Reputation: 881363
There are two ways I know of to do this. Both of them require a char*
so the string you're working with is *string
in your case (string
is the pointer to the char*
representing the string, so you have to dereference it to get the actual string).
The first is simple pointer addition, as in (*string) + 7
. This gives you the string starting at the eighth character.
The second is to get the address of the starting character, as in &((*string)[7])
.
Both of these will only "work" if you're string is at least eighth characters long. In other words, don't try to look beyond the end of the string.
Upvotes: 0
Reputation: 59699
You could pass the pointer of the whole string to the function along with an integer length, which the function will take into consideration in its logic.
Or, you can extract a specific substring (assuming you want to only trim characters off the front of the string) by using pointer arithmetic:
char * x = "Some text";
char * y;
y = x + 5;
Now, y is pointing to the string "text". http://codepad.org/icVjE6in
Or, extracting a substring with a specific start and end would require using that and strncpy.
Upvotes: 0
Reputation: 28434
char **string;
function((*string) + pos)
or
char *string;
function(string + pos)
Upvotes: 1
Reputation: 6126
(*string)[pos]
denotes the char at position pos
. You probably want (*string) + pos
instead.
Upvotes: 0
Reputation: 134841
The type of string
is char **
.
string
is of type char **
. (pointer to your string)
*string
is of type char *
. (the string itself)
**string
is of type char
. (a letter in the string)
So you want to offset into the string itself:
(*string) + pos
which will have type char *
.
Upvotes: 1