开发者

Why can't I reference a character in a string that was previously cast to void?

开发者 https://www.devze.com 2023-01-27 19:12 出处:网络
To use pthreads, I us开发者_运维技巧ed as input a char* that was cast to void* as input. If it\'s later cast to (char*) it can be printed and used normally ( (char*)var ). However, if one does (char*)

To use pthreads, I us开发者_运维技巧ed as input a char* that was cast to void* as input. If it's later cast to (char*) it can be printed and used normally ( (char*)var ). However, if one does (char*)var[i], where 'i' will help us reference a character, it doesn't. Why?

e.g. MS says 'expression must be a pointer to a complete object type'.


Because of operator precedence: the cast comes after the subscript operator.

You have to write ((char*)var)[i];.


The cast, in this case, is lower precedence than the array indexing. Instead, you would have to do something like *((char *)var + i), but the clearest approach is probably to assign it to a temporary:

 char *str = var;
 printf("%c", str[i]);


Try (char *) &var[i], but that simply gets reference from var[i]. You can't do (char *) var[i] as that actually tries to convert a char to (char *).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号