简体   繁体   中英

C program crashes on printing array

I am learning C at the moment, and am trying to build a simple interpreter. It takes one character and one number. The program below only uses 'r' for the char. The 'r' stands for the range (of the natural numbers) and the digit after it specifies the length of the range.

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("%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().

I recommend you adopt two debugging techniques:

a). Add print statements in your code so you know what's happening b). Use an interactive debugger so you can step through and see what's going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM