【问题标题】:In c Argument of type char is incompatiple with parameter type const char在 c 中,char 类型的参数与参数类型 const char 不兼容
【发布时间】:2014-07-03 18:45:45
【问题描述】:

我目前在这段代码中遇到标题错误。

void Option_3(char filename)
{ // profit for a month

    FILE *ptr_file;
    int num1, num2, num3;
    int a[31],b[31],c[31];
    int count=0;
    int i;


    ptr_file = fopen ( filename ,"r"); // error is here at file name

以后主要

void main()
{
    int select;
    char filename;
    select = 0 ;
    filename = "April.txt"; //here the equals sign is giving me the error.

【问题讨论】:

    标签: c file char constants


    【解决方案1】:

    你需要声明为char *:

    void main()
    {
        int select;
        char *filename; // Note the declaration
        select = 0 ;
        filename = "April.txt";
    

    在Option_3 的参数声明上也更改它:

    void Option_3(char *filename)
    

    原因是声明它为char 意味着您有一个变量来保存char 类型的对象。 C 中的字符序列是以'\0' 结尾的字符数组,因此char * 是正确的类型。

    更新:更合适的是将其声明为const char *,因为您不能修改字符串文字。

    【讨论】:

    • 哇,谢谢男人,在那之后真的是在捂脸。我简直不敢相信我的错误是多么愚蠢。
    • [pedantic] 编写代码的适当方法是const char *filename = "April.txt";,因为您无法更改字符串的值。
    • @EliasVanOotegem 我同意。感谢您的关注,我更新了我的答案。
    【解决方案2】:

    在 C 中,char 类型与 char * 类型不兼容。仅仅因为它们是不同的类型。根据定义,char 保证是最小的类型(大小为 1)。 char * 的大小与任何指针相同:它必须足够大以容纳内存地址:通常在 32 位系统上为 4,在 64 位系统上为 8。

    您正在将字符串常量分配给声明为char 的变量,该分配期望右手参数类似于以下内容:

    char foo = 'a';//single quotes indicate a char
    

    或者,也许更多你的想法:

    const char *foo = "April.txt";//double quotes indicative of char *
    

    注意const存储类:字符串常量不会被赋值给变量,而是filename的值将是字符串的内存地址,存储在只读 记忆。因此,它是一个const:你不能改变它:

    const char *foo = "foobar";
    foo[0] = 'F';//<-- ERROR
    

    为了能够修改值,写:

    char foo[] = "foobar";
    foo[0] = 'F';//Success!
    

    这将创建一个足够大的数组以容纳字符串,并复制字符。当然,如果你的 var 的值可能会改变,它也有可能足够大以容纳更大的字符串,在这种情况下:

    char foo[100] = "up to 100 chars";
    strcat(foo, "!!");
    

    或者,使用动态内存(但尽可能避免,因为堆速度较慢并且需要您更多关注):

    char *foo = malloc(20);//begin with 20 chars
    if (foo == NULL)
        exit( EXIT_FAILURE);//no memory could be allocated
    strcpy(foo, "foobar");//copy string value into allocated memory
    foo = realloc(foo, 50);//increase amount of allocated memory to hold 50
    if (foo == NULL)//safety first:
        exit(EXIT_FAILURE);
    strncat(foo, "some huuuuuuge string", 30);//strncat for safety, again
    

    嗯,有多种方法可以做事,这取决于您的具体需求

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 1970-01-01
      • 2019-12-16
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2020-11-19
      • 2021-01-07
      相关资源
      最近更新 更多