简体   繁体   中英

C: Make Rectangle Error

I wanted to make a simple rectangle with "-", "|", and tons of spaces. This is the code:

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

#define MAX_NUMBER 25

void draw_height(int height, int width)
{
    int i = 0;
    for(i = 0; i <= (height-1); i++) {
        printf("|");
        for(i = 0; i <= (width-1); i++) {
            printf(" ");
        }
        printf("|");
    }
}

void draw_width(int width)
{
    int i = 0;
    printf(" ");
    for(i = 0; i <= width; i++) {
        printf("_");
    }
}

void draw_height_final(int width)
{
        printf("|");
        int i = 0;
        for(i = 0; i <= (width); i++) {
            printf("_");
        }
        printf("|");

}
//make the rectangle
void make_rec(int w, int h)
{
    draw_width(w);
    draw_height(h, w);
    draw_height_final(w);
}

//initiate the program
int main(int argc, char *argv[])
{
    int rec_width;
    int rec_height;
    if(isdigit(argv[1]) && isdigit(argv[2])) {
        rec_width = (int)argv[1];
        rec_height = (int)argv[2];
        if(rec_width < MAX_NUMBER && rec_height < MAX_NUMBER) {
            make_rec(rec_width, rec_height);
        } else {
            printf("The max value is 25 for both\n");
        }
    } else {
        printf("Inputs must be numbers\n");
    }
    return 0;
}

However, when I run it in Ubuntu terminal with ./ it prints, "Segmentation fault (core dumped).

I also noticed that the terminal told me there were casting issues on line 52 and 53.

Please help!

   rec_width = (int)argv[1];
   rec_height = (int)argv[2];

Casting doesn't convert char* to int . You need to use strtol family functions to do that.

Moreover, isdigit takes an int parameter whereas you pass char* . Your condition to check if there are arguments passed can be written as:

if (argc == 3) {
   rec_width = ... /*conversion using strtol here with error checking*/
   rec_height = ... /*conversion using strtol here with error checking*/
      if(rec_width < MAX_NUMBER && rec_height < MAX_NUMBER) {
            make_rec(rec_width, rec_height);
       } else {
            printf("The max value is 25 for both\n");
       }
   }
   else {
        printf("Inputs must be numbers\n");
   }

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