简体   繁体   中英

C error while printing rectangle: Abort trap: 6

I'm trying to use a two dimensional array to print out a rectangle on screen, here's my code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int width = 6;
    int hight = 3;
    char array[5][8];

    // Print the rectangle WITHOUT using the array: 
    for(int i = 0; i <= (hight+1); i++){
        for(int j = 0; j <= (width+1); j++){
            if((i == 0 || j == 0) || ( i == (hight+1) || j == (width+1))){
                printf("A");
                array[j][i] = 'A';
            } else {
                printf("B");
                array[j][i] = 'B';
            }
        }
        printf("\n");  
    }

    // Print the rectangle using the array: 
    printf("\nRectangle from array: \n\n");

    for(int i = 0; i <= (hight+1); i++){
        for(int j = 0; j <= (width+1); j++){
            printf("%c", array[j][i]);
        }
        printf("\n");   
    }
    return 0;
}

Output:

AAAAAAAA
ABBBBBBA
ABBBBBBA
ABBBBBBA
AAAAAAAA

Rectangle from array: 

AAAAAAAA
ABBBBBBA
ABBBBBBA
ABBBBBBA
AAAAAAAA
Abort trap: 6

The rectangle is being printed correctly except for the abort trap error, where's my mistake?

You've got your array dimensions reversed.

The loops have the width as the first dimension, ranging from 0 to 7, but the first dimension has size 5. You therefore write past the end of the array triggering undefined behavior .

You want:

char array[8][5];

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