[英]C program crashes on printing array
I am learning C at the moment, and am trying to build a simple interpreter. 我目前正在学习C,并且正在尝试构建一个简单的解释器。 It takes one character and one number.
它需要一个字符和一个数字。 The program below only uses
'r'
for the char. 下面的程序仅对字符使用
'r'
。 The 'r'
stands for the range (of the natural numbers) and the digit after it specifies the length of the range. 'r'
代表范围(自然数),后面的数字指定范围的长度。
Example Execution: 执行示例:
Enter:
r 9
0 1 2 3 4 5 6 7 8
What happens instead: 相反会发生什么:
Enter:
r 9
And here the program crashes. 程序崩溃了。 So I believe the error lies in the printing of the array.
因此,我相信错误在于阵列的打印。
The code in question is here: 有问题的代码在这里:
#include <stdio.h>
#include <stdlib.h>
int* range(int i) {
int *a=(int*) malloc(i * sizeof(int));
int j;
for(j=0;j<i;j++)
a[j]=j;
return a;
}
void printArray(int a[], int length) {
int i;
printf("\n");
for(i=0;i<length;i++)
printf("%d ", a[i]);
}
int main() {
char c;
int n = 1;
while(n>=0){
printf("\nEnter:\n\t");
scanf("%c %d", c, n);
if(c='r')
printArray(range(n), n);
}
return 0;
}
So what is causing the program to crash? 那么,是什么导致程序崩溃?
Your arguments to scanf are wrong, you need 您对scanf的争论是错误的,您需要
scanf("%c %d",&c, &n);
Your fundamental problem here is that you have no evidence about where the crash is happening, as it happens I bet it's in scanf(). 您的基本问题是,您没有崩溃发生在哪里的证据,因为我敢肯定它在scanf()中。
I recommend you adopt two debugging techniques: 我建议您采用两种调试技术:
a). 一种)。 Add print statements in your code so you know what's happening b).
在代码中添加打印语句,以便了解发生了什么b)。 Use an interactive debugger so you can step through and see what's going on.
使用交互式调试器,以便您可以逐步进行并查看发生了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.