简体   繁体   English

从const char *到char *的无效转换

[英]invalid conversion from `const char*' to `char*'

#include <stdio.h>
#include <string.h>
#include <conio.h>
#define SIZE 20

int main( void )
{
    int n; //number of characters to be compared
    char s1[ SIZE ], s2[ SIZE ];
    char *results_word;

    printf( "Enter two strings: " );
    gets( s1 );
    gets( s2 );
    printf( "\nEnter the number of characters to be compared: " );
    scanf( "%d", &n );

The problem starts here 问题从这里开始

    results_word = 
                 strncmp( s1, s2, n ) > 0 ? " greater than " : 
                 strncmp( s1, s2, n ) == 0 ? " equal to " : " smaller than " ;

    printf( "\n%sis%s%s", s1, results_word, s2 );

    getche();
    return 0;
}//end function main

So why doesn't result_word get the corresponding string ? 那为什么result_word没有得到相应的字符串呢?

The C++ error message you are getting says it all: 您收到的C ++错误消息说明了一切:

invalid conversion from `const char*' to `char*' 从const char *到char *的无效转换

You are trying to assign some constant "<literal>" to the non constant results_word . 您正在尝试将一些常量"<literal>"分配给非常量results_word

Change 更改

char *results_word;

to be 成为

const char *results_word;

and it will work. 它会工作。

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

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