简体   繁体   English

如何将字符串值传递给C中的函数

[英]How can I pass a string value to a function in C

This bothers me. 这困扰着我。 It gives me a warning of 它给了我一个警告

passing argument 1 of ‘funcName’ discards qualifiers from pointer target type

however, the program to run just fine and printing the submitted value. 但是,该程序可以正常运行并打印提交的值。

The functions are the following 功能如下

void funcName(char *str) {
    printf("%s", str);
}

void main() {
    funcName("Hello world");
}

output is Hello world. 输出是Hello world。

It's because "Hello, world" is constant, so change the function to 这是因为"Hello, world"是常量,因此将函数更改为

void funcName(const char *text) 
{
    printf("%s\n", text);
}

String literals are constant, they are stored in a read only memory section of your program, passing the pointer without const means that you can accidentally modify it inside the target function, if you do so, that would cause undefined behavior , and the compiler is trying to protect you from that. 字符串文字是常量,它们存储在程序的只读存储区中,传递不带const的指针意味着您可能会意外地在目标函数内部对其进行修改,否则将导致未定义的行为 ,并且编译器为试图保护您免受此伤害。

Also, void main() is not a standard compliant valid signature for main() , you can find it in old books, previous to the standard, but now it's no longer accepted, accepted and standard signatures are 此外, void main()是不符合标准的有效签名main()你可以找到它的旧书,以前的标准,但现在它不再被接受,认可和标准签名

  • int main(void) If you don't handle command line arguments. int main(void)如果不处理命令行参数。
  • int main(int argc, char **argv) To handle argc parameteres stored in argv that where passed in the command line. int main(int argc, char **argv)处理在命令行中传递的argv中存储的argc参数。

It seems that the problem is that this C program is compiled as a C++ program. 看来问题在于此C程序被编译为C ++程序。

In C++ string literals have types of constant character arrays. 在C ++中,字符串文字具有常量字符数组的类型。 So if in a C++ program you supply a string literal as an argument to a function that has the corresponding parameter without the qualifier const then the compiler will issue a message. 因此,如果在C ++程序中提供字符串文字作为函数的参数,而该函数具有不带限定符const的相应参数,则编译器将发出一条消息。

If to compile the program as a C program then the code is valid because in C string literals have types of non-constant character arrays and the compiler should not issue a diagnostic message relative to qualifiers. 如果将程序编译为C程序,则该代码是有效的,因为在C字符串文字中具有非恒定字符数组的类型,并且编译器不应发布有关限定符的诊断消息。

Nevertheless in any case it is better to declare the function like 不过无论如何,最好将函数声明为

void funcName( const char *str );
               ^^^^^^

because in this case the user of the function can be sure that the string passed to the function will not be changed. 因为在这种情况下,函数的用户可以确保传递给函数的字符串不会更改。

Take into account that function main without parameters shall be declared in C like 考虑到没有参数的函数main应该像C一样声明

int main( void )

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

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