C 数组索引0处的值即使在其定义的块的范围内也会不断重置
我用C编写了一个简单的程序,其功能是在大小为3的整数数组中添加或删除一个数字。数组的所有成员都初始化为-1 用户必须从菜单中选择适当的选项,并可以插入、删除、修改或查看数组元素 选择选项1添加元素。在此,程序将首先在数组中查找负数,然后用用户提供的数字替换负数,例如:2。因此,此处数组的第一个元素应被2覆盖,即数组[0]=2 选择选项4以查看修改后阵列的元素 令我惊讶的是,数组的第一个元素是0。我彻底检查了整个程序,看是否意外修改了数组中的第一个元素,但找不到任何内容。我无法找出问题所在 注意:代码是在linux平台OpenSUSE上编译的。我在代码中添加了一些调试printf。另外,我发现当我更改数组int array[3]的声明位置时,={-1,-1,-1};把它放在所有变量声明的末尾,程序按预期运行。但我仍然想知道失败的原因C 数组索引0处的值即使在其定义的块的范围内也会不断重置,c,linux,C,Linux,我用C编写了一个简单的程序,其功能是在大小为3的整数数组中添加或删除一个数字。数组的所有成员都初始化为-1 用户必须从菜单中选择适当的选项,并可以插入、删除、修改或查看数组元素 选择选项1添加元素。在此,程序将首先在数组中查找负数,然后用用户提供的数字替换负数,例如:2。因此,此处数组的第一个元素应被2覆盖,即数组[0]=2 选择选项4以查看修改后阵列的元素 令我惊讶的是,数组的第一个元素是0。我彻底检查了整个程序,看是否意外修改了数组中的第一个元素,但找不到任何内容。我无法找出问题所在 注意:
#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的指针,但您提供了指向无符号字符的指针
当参数与格式字符串不匹配时使用会产生未定义的行为。
如果您是使用-Wall选项编译的,编译器应该警告您这一点
顺便说一句:你发布的代码没有编译:
case 4:
printf("The numbers in the array are\n", );
^ problem here
您的代码没有从编译错误中编译部分,在使用gcc和-Wall时,至少对我来说还有一个警告。你考虑过这个警告吗?谢谢Michael的回复。在发布代码时,我删除了一些调试打印,这可能会留下错误的逗号。