简体   繁体   中英

C++ char pointer to char variable

I'm given a method header as so:

char* thisMethod(char* input){}

is it possible to say,

char var = input[0];

? I know that "input" will be in the form of a char array.

I'm obviously new to C++ pointers are throwing me off. I tried researching how to work with char pointer function arguments but couldn't find anything specific enough to help. Thanks for the help.

There is a misconception that may lead you into further troubles:

I know that "input" will be in the form of a char array.

NOPE: By the scope of that function, input is a pointer to a character . The function has no way to know where such a pointer comes from.

If it has been taken from an array upon calling the function than it will be a pointer to the first element of that array .

Because pointer have an arithmetic that allows to add offsets and because the [] operator applied to pointers translates as a[b] = *(a+b) by definition, in whatever code, if a is a pointer, *a and a[0] are perfect synonymous.

Think to an array as a sequence of boxes and a pointer as your hand's index finger

adding an offset to a finger (like finger+2 ) means " re-point it aside " and de-referencing it (like *finger ) means "look inside what it points to ".

The [] operator on pointers is just a shortcut to do both operations at once.

Arrays are another distinct thing. Don't think to them when dealing with pointers, since -in more complex situations, like multidimensional array or multi-indirection pointers - the expression a[b][c] won't work anymore the same way.

As long as it's inside the function and input points to something valid ( not NULL / nullptr and not a garbage location ) then doing char var = input[0]; is just fine. It's the same as char var = *input .

PS If it's supposed to be a string I recommend using std::string .

There are two ways to get a value from a pointer, * and [] . The following are equivalent:

char var1 = *input;
char var2 = input[0];

Using the brackets is more common when you know you were passed an array, since it allows you to supply an index. You need some way of knowing where the end of the array is so that you don't attempt any access past it, your function is missing that important detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM