What does my_string(char* s) mean?
Please tell me what does the parameter (char* s) means?? Can it accept an array of characters or it will just accept pointers. Please also tell how can i make this to accept an array of strings and then 开发者_运维问答dynamically assign memory depending on the length of the string.
Technically, it's a pointer to a single char
variable. However, it can also be the pointer to the first element of an array of char
values. You can increment and decrement the pointer to move through the string (s++
or s--
) as long as you don't go beyond the ends.
You can also use indexing without changing the pointer, such as s[14] = 'a';
.
Using it as a pointer to a char
array is usually the case when you're dealing with C-style strings.
In addition, a char
array will decay to the pointer to its first element under many circumstances, such as passing to a function:
void fn (char *s) {
printf ("%s\n", s);
}
:
char xyz[50];
strcpy (xyz, "Hello");
fn (xyz);
For an array of strings in C, you would use char **
, a pointer to and array of char
pointers.
For C++, you should probably ditch char
pointers (for strings) and pass-by-pointer altogether. Use std::string
and reference types.
how can i make this to accept an array of strings
C++ solution:
void foo(std::vector<std::string> const& strings);
C solution:
void foo(const char **strings);
char* s means that s is a pointer to a memory location where characters are stored. Yes, it will accept arrays of characters, such in this example:
void func(char* s)
{
}
int main()
{
char arr[10] = {0};
func(arr);
return 0;
}
To answer how to make it to accept an array of strings, please tell what you understand by strings. Is it the std::string class, or char*?
char* s
means that s
is pointing to a single char
variable or to an array of char
's (better known as char pointer). Also to add, a string is basically an array of char
s.
To pass a char array to a method that accepts char pointer and/or array of chars, you can do something like this:
void foo(const char** string) {
}
int main() {
char[] s = "My String";
foo(&s);
}
精彩评论