C 打印用户输入阵列
有人能告诉我为什么不打印阵列吗?我不知道我的打印功能出了什么问题。在将其他部分添加到代码中之前,我希望确保它工作正常。我猜我没有正确设置数组&这就是为什么没有打印出来C 打印用户输入阵列,c,arrays,C,Arrays,有人能告诉我为什么不打印阵列吗?我不知道我的打印功能出了什么问题。在将其他部分添加到代码中之前,我希望确保它工作正常。我猜我没有正确设置数组&这就是为什么没有打印出来 #define NUMSTU 50 #include <stdio.h> //function prototype void printdata(); //Global variables int stuID[NUMSTU]; int stuCount; int totStu; int main () {
#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);
}
}
#定义NUMSTU 50
#包括
//功能原型
void printdata();
//全局变量
int stuID[NUMSTU];
整数计数;
国际托斯图;
int main()
{
int stuCount=0;
int-totStu=0;
国际学生;
//提示用户输入课堂上的学生人数
printf(“请输入课堂上的学生人数:”);
scanf(“%d”和totStu);
对于(stuCount=0;stuCount您在这里有多个错误。
首先,由于这一行,您应该得到一个越界异常
(在高级编程语言中):
stuId
是一个初始长度为NUMSTU
的数组。
您试图在NUMSTU
中访问它,即使它有可访问的插槽
仅在0
和(NUMSTU-1)
之间
你可能想做这件事:
stuId[stuCount] = studentId;
在打印中,您只需再次打印阵列的位置
再说一遍,而不是:
print("%d", stuId);
做:
哦,是的,还有第三个错误,这里:
int stuCount = 0;
int totStu = 0;
stuCount
和totStu
已声明为全局变量
(意味着每个功能都可以访问它们)。
您要做的是定义具有相同名称的新变量,
但不能被其他功能访问。
所以你应该决定它们是全球性的,还是地方性的。
无论如何,您应该将其更改为:
stuCount = 0;
totStu = 0;
现在它应该可以工作了。stuID[NUMSTU]=studentID;
有未定义的行为。您正在写入一个越界元素。printf(“%d”,stuID)
有未定义的行为。printf
%d
接受一个int
,但你传递的是一个int*
。你有两个变量称为totStu
。其中只有一个变量的值非零值。谢谢-我做了这些更正。格式化/缩进…………这是C;你不会得到“越界”的例外ons-你得到你得到的任何东西,这可能是一个例外,也可能是编译器决定的任何东西。
int stuCount = 0;
int totStu = 0;
stuCount = 0;
totStu = 0;