简体   繁体   English

带有const char的puts()问题

[英]puts() questions with const char

I'm having trouble understanding how c uses puts() to display parts of a message. 我在理解c如何使用puts()显示消息的一部分时遇到了麻烦。 Two ways which I would consider equivalent do not work the same way with the function. 我认为等效的两种方式在函数中的作用方式不同。 For example 例如

 void skippie(char *msg)
 {
    puts(msg + 6);
 }

 char *msg = "Don't call me!";
 skippie(msg);

This compiles fine, however this does not 这样可以编译,但是不可以

void skippie(char *msg)
{
    puts(msg[6]);
}

char *msg = "Don't call me!";
skippie(msg);

how does puts() distinguish between the two and only compile for one? puts()如何区分两者并仅针对其中之一进行编译? The compiler complains that it wants a "const" char but even if I try and use that syntax it fails. 编译器抱怨它想要一个“ const”字符,但是即使我尝试使用该语法,它也会失败。 Can anyone explain this? 谁能解释一下?

The index operator also dereferences the pointer, so 索引运算符还会取消引用指针,因此

msg[6] is equivalent to *(msg + 6) , not msg + 6 . msg[6]等效于*(msg + 6) ,而不是msg + 6

Furthermore, you cannot pass a const char* to a function, while it expects a char* . 此外,您不能将const char*传递给函数,而它需要char* ie, you also have to update the function signature. 即,您还必须更新功能签名。

msg + 6 is not the same as msg[6]. msg + 6msg[6].

As per your code, msg+6 is a char * , while msg[6] represents a char . 根据您的代码, msg+6char * ,而msg[6]代表char

Quoting from the man page of puts() , the syntax is puts()手册页中引用,语法为

int puts(const char *s);

so, the argument of puts() needs to be a const char * , not a char . 因此, puts()的参数必须是const char * ,而不是char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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