Kaz
Kaz

Reputation: 39

C programming - Initialization makes integer from pointer without a cast

Having trouble with some command line argurments, basically just trying to make a rectangle using command line argrumnents. Here's what I've got

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

int main(int argc, char *argv[]){

    int x;
    int y;
    int i;
    int j;

    x = atoi(argv[1]);
    y = atoi(argv[2]);

    fprintf(stderr, "Height & Width Needed\n", argv[0]);

    return 1;

    for(i = 0; i < x; i++)
        for(j = 0; j < y; j++)
            printf("*");
        printf("\n");

    return 0;
}

I know this is amateur hour but I'm just starting out. Added stderr for argv[0] statement, included atio, every time compile I just get my usage statement. I tried adding curly braces on my outer loop only, and then on the outer and inner loop, still just getting my stderr every time I run with commands.

Upvotes: 0

Views: 615

Answers (1)

Stargateur
Stargateur

Reputation: 26717

C is not like Python, you must put bracket to create block. There is no if structure around your return 1; so it will be always executed.

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

int main(int argc, char *argv[])
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s height width\n", argc > 0 ? argv[0] : "");
        return 1;
    }
    int x = atoi(argv[1]);
    int y = atoi(argv[2]);

    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            printf("*");
        }
        printf("\n");
    }
}

Note: atoi() don't detect error, use strtol() instead.

Upvotes: 1

Related Questions