gpt4 book ai didi

c - 为什么我的数组中的值不安全?

转载 作者:行者123 更新时间:2023-11-30 15:38:14 25 4
gpt4 key购买 nike

我是 C 新手。我想创建一个程序,用户可以在其中用数字填充数组,将特定数字设置到某个数组寄存器中或读取寄存器的值。到目前为止,除了阅读值(value)之外,一切正常。我总是得到 0 返回,为什么?这是我的 getValue() 代码;

void getValues(int getArray[]){



fflush(stdin);
printf("which slot do you want to read?\n");
gvinput = getchar();
ptr = getArray[gvinput];
printf("The value is: %d \n",ptr);
start();
}

这是完整的代码..

#include <stdio.h>
#include <stdlib.h>


int* ptr;
int list[200];
int x = 0;
int i = 0; // variable used by for-Loop in setList
int j = 0; // variable used by for-Loop in getList
int c; // C used for new Game
int input;
int g1; //Value for getValue
int option; //start Value
int gvinput;


int main()
{
start();
return 0;
}


void setList(int sizeOfList)
{
for (i = x; i <= sizeOfList; i++)
{

list[i] = i;

}
}

void getList()
{
for(j = x; j < i ; j++ )
{
printf("At %d we got the value %d with the adress %d\n",j,list[j],&list[j]);
}
}

void startList()
{
fflush(stdin);
printf("Please enter number between 0 and 30\n ");
scanf("%d",&input);
if(input > 30 || input == 0)
{
printf("The Number is not between 0 and 30\n");
startList();
}
setList(input);
getList();
fflush(stdin);
start();
}



void setValues(int l[])
{
fflush(stdin);
int v;
int loc;
printf("please enter what value you want to safe\n");
scanf("%d",&v);
fflush(stdin);
printf("Where do you want to save it?\n");
scanf("%d",&loc);
l[loc] = v;
printf("we got at slot %d the value %d\nThe Adress is: %d.",loc,l[loc],&l[loc]);
start();
}

void getValues(int getArray[]){



fflush(stdin);
printf("which slot do you want to read?\n");
gvinput = getchar();
ptr = getArray[gvinput];
printf("The value is: %d \n",ptr);
start();
}

void start(){
fflush(stdin);
printf("[L] = generate Slots\n");
printf("[S] = set a Value at specific slot\n");
printf("[G] = get a Value from a specific slot\n");
option=getchar();
if(option == 'L'){
startList();
}
if(option == 'S'){
setValues(list);
}
if (option =='G'){
getValues(list);
}
}

如果有人可以提供帮助并提供提示,那就太好了

最佳答案

您的程序因使用 getchar() 而变得彻底困惑。当您按下 GEnter 等键时,getchar() 返回两个个字符。第一次调用将返回 'G',然后下次调用 getchar() 时将返回 '\n'(Enter 键)。

要解决此问题,请将对 getchar() 的调用替换为以下代码:

char buf[80];
fgets(buf, sizeof(buf), stdin);
option = buf[0];

调用 fgets() 将获取整行文本,包括 Enter 按键,然后 option = buf[0]; 提取该行中键入的第一个字符。

完成此操作后,您可以删除所有 fflush(stdin),这在技术上(根据 C 标准)是未定义的行为,并且并不真正执行您想要的操作。

编辑:您还需要对 scanf() 的调用执行相同的操作。该功能根本不是为了交互式使用而设计的。如上使用fgets(),然后调用atoi()将输入的字符串转换为int。

另一个编辑:您正在使用

gvinput = getchar();

它分配输入到gvinput中的字符的ASCII值。如果您输入 4,则 gvinput 将得到 52,而不是 4。使用与 setValues() 中使用的相同方法来获取 的值loc

关于c - 为什么我的数组中的值不安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21869099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com