从“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 );
问题从这里开始
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
那为什么result_word没有得到对应的字符串呢?
您收到的 C++ 错误消息说明了一切:
invalid conversion from `const char*' to `char*'
您正在尝试将某个常量 "<literal>"
分配给非常量 results_word
。
改变
char *results_word;
成为
const char *results_word;
它会起作用。
#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 );
问题从这里开始
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
那为什么result_word没有得到对应的字符串呢?
您收到的 C++ 错误消息说明了一切:
invalid conversion from `const char*' to `char*'
您正在尝试将某个常量 "<literal>"
分配给非常量 results_word
。
改变
char *results_word;
成为
const char *results_word;
它会起作用。