问题描述
#include <stdlib.h>
#include <stdio.h>
void arraydescending(int array[]){
for (int j=0; j<9; j++){
for (int i=0; i<8; i++)
{
if(array[i]<array[i+1]){
int swapper = array[i+1];
array[i+1]=array[i];
array[i]=swapper;
}
}
}
for (int c=0; c<9; c++){
printf("%d",array[c]);
}
}
void arrayreverse(int array[])
{
for(int i = 0; i<4; i++)
{
int swapper = array[i];
array[i] = array[8-i];
array[8-i] = swapper;
}
for (int c=0; c<9; c++){
printf("%d",array[c]);
}
}
int main()
{
int choice;
printf("Please enter your choice:");
scanf("%d",&choice);
if(choice == 1)
{
int mynumberarray[9] = {1,1,2,4,7};
int choice_2;
printf("Write 1 for reverse order,write 2 for descending order:");
scanf("%d",&choice_2);
if(choice_2 == 1)
{
arrayreverse(mynumberarray);
}
else if(choice_2 == 2)
{
arraydescending(mynumberarray);
}
else
{
printf("Invalid choice");
}
}
else if(choice == 2){
int userarray[9];
char * user_entry;
printf("Please enter your school no (9 digits):");
scanf("%s",user_entry);
for(int i = 0; i < 9; i++)
{
userarray[i] = user_entry[i] - '0';
}
int choice_2;
printf("Write 1 for reverse order,&choice_2);
if(choice_2 == 1)
{
arrayreverse(userarray);
}
else if(choice_2 == 2)
{
arraydescending(userarray);
}
else
{
printf("Invalid choice");
}
}
else
{
printf("Invalid choice");
}
return 0;
}
当我用 gcc -std=c99 编译这段代码时,它可以正确运行;但是我的朋友有 DevC 5.11 版本可以编译代码,但它在他的 DevC 中无法正确运行(它在第二次 scanf 中退出程序)。两者都编译但为什么它不能在 DevC 5.11 中使用编译器 gcc 4.9.2 运行?我正在等待您的建议,因为我不明白背后的原因,我的代码看起来没有任何错误。
解决方法
你的程序有未定义的行为,至少因为在这段代码片段中
char * user_entry;
printf("Please enter your school no (9 digits):");
scanf("%s",user_entry)
您正在使用具有不确定值的未初始化指针 user_entry
。您需要声明一个足够大的字符数组,您将在其中读取一串数字。不要忘记在数组中为读取字符串的终止零字符保留一个空格。