我用C写了一个简单的程序,其功能是在大小为3的整数数组中添加或删除一个数字。数组的所有成员都初始化为-1。
用户必须从菜单中选择适当的选项,并且可以插入、删除、修改或查看数组的元素。以下是我编译程序后遵循的步骤。
选择选项1来添加元素。(这里,程序将首先在数组中查找负数,然后用用户提供的数字替换该负数,例如:2.so数组的第一个元素应被 2 覆盖,即
array[0] = 2
)选择选项 4 以查看修改后的数组的元素。
令我惊讶的是,数组的第一个元素是 0。我彻底检查了整个程序是否意外修改了数组中的第一个元素,但找不到任何内容。我无法找出问题所在。
注意:代码已在linux平台(OpenSUSE)上编译。我在代码中添加了一些调试printf。此外,我发现当我更改数组声明的位置时“int array [3] = {-1,-1,-1};
"并将其放在所有变量声明的末尾,程序按预期运行。但我仍然想知道原因失败
#include <stdio.h>
unsigned char ShowMenu();
int main()
{
ShowMenu();
return 0;
}
unsigned char ShowMenu()
{
int array[3] = {-1,-1,-1};
unsigned char Operation = 0;
int Number = 0;
unsigned char Index = 0;
do
{
printf("number atlocation 1 is %d\n",array[0]);
printf("Input Operation to be performed\n");
printf("1.Add\n2.Remove\n3.Modify\n4.View all\n5.Exit\n");
scanf("%d",&Operation);
printf("number atlocation 1 is %d\n",array[0]);
switch(Operation)
{
case 1:
printf("enter a positive number\n");
scanf("%d",&Number);
//check if the number is positive
if(Number > 0)
{
for(Index = 0;Index < 3;Index++)//check for neg number positions
{
if (array[Index] < 0)
{
array[Index] = Number;
printf("Number added at location %d\n",Index);
break;
}
else
{
if (Index == 2)
{
printf("No more elements can be added\n");
}
else
{
//do nothing
}
}
}
}
else
{
printf("the number is negative\n");
}
Index = 0;
Number = 0;
printf("leaving case 1 :%d\n",array[0]);
break;
case 2:
printf("Input the number to remove\n");
scanf("%d",&Number);
for(Index = 0;Index < 3;Index++)//check for neg number positions
{
if (array[Index] == Number)
{
array[Index] = -1;
printf("Number removed at location %d\n",Index);
break;
}
else
{
if(Index == 2)
{
printf("Number couldn be found\n");
}
else
{
//do nothing
}
}
}
Index = 0;
Number= 0;
break;
case 3:
printf("Input the ponumber to find and replace\n");
scanf("%d",&Number);
//this is not complete
break;
case 4:
printf("The numbers in the array are\n",);
for(Index = 0;Index < 3;Index++)//check for neg number positions
{
printf("Index %d : %d\n",Index,array[Index]);
}
Index = 0;
Number= 0;
break;
case 5:
printf("Operation complete\n");
break;
default:
printf("Invalid input\n");
}
}
while(Operation != 5);
return Operation;
}
最佳答案
你有
unsigned char Operation = 0;
然后你使用
scanf("%d", &Operation);
因此你需要
int Operation = 0;
%d
格式说明符需要一个指向 int
的指针,但您提供了一个指向 unsigned char
的指针。
使用scanf
当参数与格式字符串不匹配时,会产生未定义的行为。
如果您使用 -Wall
选项进行编译,您的编译器应该会警告您这一点。
顺便说一句:您发布的代码无法编译:
case 4:
printf("The numbers in the array are\n", );
^ problem here
关于c - 即使数组索引 0 处的值位于其定义的 block 的范围内,它也会不断重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40355904/