【问题标题】:Printing user input array打印用户输入数组
【发布时间】:2017-05-07 16:09:09
【问题描述】:

有人可以告诉我为什么这不打印数组吗?我不知道我的打印功能有什么问题。在将其他部分添加到我的代码之前,我想确保它正常工作。我猜我没有正确设置数组,这就是为什么没有打印出来。

#define NUMSTU 50

#include <stdio.h>

//function prototype
void printdata();

//Global variables

int stuID[NUMSTU];
int stuCount;
int totStu;

int main ()
{
   int stuCount = 0;
   int totStu = 0;
   int studentID;
    //Prompt user for number of student's in class

    printf("Please enter number of student's in class:");
    scanf ("%d", &totStu);

   for (stuCount = 0; stuCount <totStu; stuCount++)
   {    
   //Prompt user for student ID number

   printf("\n Please enter student's ID number:");
  scanf("%d", &studentID);
  stuID[NUMSTU] = studentID;

  }

 //Call Function to print data
 printdata();

 return 0;
 }//end main


 void printdata(){

 //This function will display collected data
 //Input: Globals stuID[NUMSTU]
//Output: none



//Display column headers
printf("\n\n stuID\n");

//loop and display student ID numbers
for (stuCount = 0; stuCount <totStu; stuCount++){
printf("%d", stuID);
}
}

【问题讨论】:

  • stuID[NUMSTU] = studentID; 具有未定义的行为。您正在写入越界元素。
  • printf("%d", stuID); 具有未定义的行为。 printf %d 接受 int,但您传递的是 int *。
  • 你有两个变量叫做totStu。其中只有一个具有非零值。
  • 谢谢 - 我做了这些更正。
  • 格式化/缩进......

标签: c arrays


【解决方案1】:

你在这里犯了不止一个错误。 首先,由于这条线,您应该得到一个超出边界的异常 (在高级编程语言中):

stuId[NUMSTU] = studentId;

stuId 是一个初始长度为NUMSTU 的数组。 您正在尝试在 NUMSTU 中访问它,即使它有可访问的插槽 仅在0 和(NUMSTU-1) 之间。

你可能想做这件事:

stuId[stuCount] = studentId;

在打印中,您只是再次打印数组的位置 然后再次。而不是:

print("%d", stuId);

做:

print("%d", stuId[stuCount]);

哦,是的,还有第三个错误,在这里:

int stuCount = 0;
int totStu = 0;

stuCount 和 totStu 已被声明为全局变量 (意味着每个函数都可以访问它们)。 您正在做的是定义具有相同名称的新变量, 但不能被其他函数访问。 所以你应该决定它们是全局的还是本地的。 无论如何,您应该将其更改为:

stuCount = 0;
totStu = 0;

现在应该可以了。

【讨论】:

  • 这是C;你不会得到“越界”异常——你会得到你得到的任何东西,这可能是一个异常,也可能是编译器决定的任何其他东西。
猜你喜欢
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 2013-10-03
  • 1970-01-01
相关资源
最近更新 更多