Ass*_*ins 0 c string pointers char
(char* )str下面的代码做了什么?
/**
* Main file
*/
#include <assert.h>
#include <mylib.h>
int main()
{
const char str[] = "this is my first lab\n";
int ret=1;
ret = my_print((char *)str, sizeof(str));
assert(!ret);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码由我的教师编写.my_print是一个接收指向字符串的指针和该字符串大小的函数.我很困惑为什么我们必须使用(char*)str将字符串传递给my_print函数.它实际上做了什么?
Thi*_*ter 10
它抛弃了const.
这意味着它会使程序崩溃,以防my_print修改该字符串,因为它的内存可能被标记为只读.因此,const通过强制转换删除修改器通常是个坏主意.
在你的情况下,它看起来有点像谁实现my_print不认为要打印的字符串永远不会被修改,因此不会让它接受一个const char *参数.
那么你应该做什么而不是强制转换是改变my_print接受a const char *而不是a char *作为其第一个参数的定义.