c - 通过函数时获取垃圾而不是变量

标签 c scanf

<分区>

所以这可能是一个简单的修复方法,但我似乎无法弄清楚。

User enters N to enter a number. Then the user enters F to print the Fibonacci sequence to that number.

我的原始打印 0-20(工作代码)被注释掉了。我尝试以相同的方式设置斐波那契数列,但在打印数字时出现乱码。我现在将它设置到它在 for 循环之前暂停的位置,这样我就可以看到它得到的数字。

#include <stdio.h>

char menu();
int read_int(int number);
void display(int answer);

int main(int argc, char ** argv) {
    int number = 0;     
    char choice = 'O';
    while (choice != 'X'){
        choice = menu();    

        if (choice != 'N' && choice != 'F' && choice != 'X') {
            printf("Invalid Input. Enter N, F, or X\n");
        }

        else if (choice == 'N') {
            number = read_int(number);
            printf("\nNumber equals: ");
            printf("%d", number);           
        }

        else if (choice == 'F') {
            //printf("\nNumber equals: ");
            //printf("%d", number);         
            display(number);            
        }
    }
}


char menu () 
{
    char i; 
    printf("\nEnter N to enter an integer from 0 to 20\nEnter F to display the first N+1 numbers (beginning with zero) on the console \nEnter X to quit the program \n");

    printf("Your Choice: ");
    scanf("%s",  &i);
    return i;
}   

int read_int(int number)
{
    number = 0;
    printf("\nEnter an integer 0-20: ");
    scanf("%d", &number);
    if (number >=0 && number <=20)
        return number;
    else{
        printf("Enter a valid number between 0 and 20");    
        return read_int(number);
    }
}

void display(int answer)
{
//  int count = 0;
//  //printf("\nNumber equals: ");
//  //printf("%d", answer); 
//  //int toprint = answer;
//  while (count <= answer){            
//      printf("%d",count);
//      printf(" , ");
//      count=count+1;
   //int n = answer;
   int n = 0;
   n = answer;
   int first = 0, second = 1, next, c;

   //printf("Enter the number of terms\n");


   printf("\nNumber equals: ");
   printf("%d", &answer);
   scanf("%d",&n);
   for ( c = 0 ; c < answer ; c++ )
   {
      if ( c <= 1 )
         next = c;
      else
      {
         next = first + second;
         first = second;
         second = next;
      }
      printf("%d\n",next);
   } 

   //return 0;
}

最佳答案

在你的例子中,问题产生于

 scanf("%s",  &i);

%s 需要一个指向 char 数组的指针,而不是单个 char 元素。即使对于单个 char 输入,这也会造成内存溢出,从而导致 undefined behaviour。 .

您可以将其替换为

 scanf(" %c", &i);

另外,printf("%d", &answer); 看起来不对,我想你的意思不是说 & 在那里。

关于c - 通过函数时获取垃圾而不是变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31345899/

相关文章:

c - 循环扫描直到回车

c - 将输入发送到 C 程序并打印它们

编译器/链接错误: Freedup

c - 在 C 中调用新的 NotifyOSD 框架?

c - 在什么情况下 Windows 临界区可能有一个负的锁定计数?

c - 为什么最后一行和最后一列的行为是这样的?

c - 如何使用 fscanf 从文本文件复制到结构

在 while 循环中使用 scanf() 检查输入类型

c - fgets inside while循环用于登录验证

c++ - 从 C++ 生成 C 包装器?